Microsoft Integration
Overview
The Microsoft integration allows MEGDocs users to connect their Microsoft accounts to enable browser-based document editing via M365. This feature uses OAuth 2.0 authentication to securely access M365 files without storing user passwords.
Architecture
OAuth Flow
User Initiates Connection
User clicks “Connect to Microsoft” in Account Settings (
/accounts/account/microsoft/)Authorization Request
Application redirects user to Microsoft authorization URL with:
Client ID
Redirect URI
Requested scopes (User.Read, Files.ReadWrite.All)
State parameter (CSRF protection)
User Grants Permission
User signs in to Microsoft and grants permissions
Authorization Callback
Microsoft redirects back to
/auth/oauth2/microsoft/callback/with authorization codeToken Exchange
Application exchanges authorization code for:
Access token (short-lived, ~1 hour)
Refresh token (long-lived, for obtaining new access tokens)
Token Storage
Tokens are stored in database as an
Oauth2Integrationrecord
Security
State Parameter
OAuth flow uses cryptographically secure state parameter to prevent CSRF attacks:
Generated using
secrets.token_urlsafe(32)()Stored in user session during authorization
Validated during callback
Token Expiration
Access tokens expire after ~1 hour
Refresh tokens are long-lived but can be revoked
5-minute buffer used when checking token expiration status
User Guide
Permissions
When connecting, the following Microsoft permissions are requested:
User.Read: Read your profile information
Files.ReadWrite.All: Read and write your M365 files
Troubleshooting
User Can’t Connect
Problem: User gets error when trying to connect Microsoft
Solutions:
Verify environment variables are set correctly
Check that redirect URI in Azure Portal matches the format
https://audits{SUBDOMAIN}.megsupportools.com/auth/oauth2/microsoft/callbackEnsure Azure app has correct API permissions
Check application logs for specific error messages
Token Refresh Fails
Problem: User gets errors about expired tokens
Solutions:
User should try disconnecting and reconnecting Microsoft
Check if refresh token has been revoked in Microsoft account settings
Verify app still has valid credentials in Azure Portal