============================ 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. .. contents:: Table of Contents :local: :depth: 2 Architecture ============= OAuth Flow ----------- 1. **User Initiates Connection** User clicks "Connect to Microsoft" in Account Settings (``/accounts/account/microsoft/``) 2. **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) 3. **User Grants Permission** User signs in to Microsoft and grants permissions 4. **Authorization Callback** Microsoft redirects back to ``/auth/oauth2/microsoft/callback/`` with authorization code 5. **Token Exchange** Application exchanges authorization code for: * Access token (short-lived, ~1 hour) * Refresh token (long-lived, for obtaining new access tokens) 6. **Token Storage** Tokens are stored in database as an ``Oauth2Integration`` record Security ========= State Parameter ---------------- OAuth flow uses cryptographically secure state parameter to prevent CSRF attacks: * Generated using :func:`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**: 1. Verify environment variables are set correctly 2. Check that redirect URI in Azure Portal matches the format ``https://audits{SUBDOMAIN}.megsupportools.com/auth/oauth2/microsoft/callback`` 3. Ensure Azure app has correct API permissions 4. Check application logs for specific error messages Token Refresh Fails -------------------- **Problem**: User gets errors about expired tokens **Solutions**: 1. User should try disconnecting and reconnecting Microsoft 2. Check if refresh token has been revoked in Microsoft account settings 3. Verify app still has valid credentials in Azure Portal