====================================
Microsoft Integration Setup Guide
====================================
This guide walks through setting up the Microsoft integration for MEGDocs, including
creating an Azure App Registration and configuring the necessary environment variables.
.. contents:: Table of Contents
:local:
:depth: 2
Prerequisites
==============
Before starting, you'll need:
* An Azure account with permissions to register applications
* Access to your MEGDocs deployment environment variables
* Your MEGDocs domain URL (e.g., ``https://audits.megsupporttools.com``)
Step 1: Create Azure App Registration
=======================================
1. Navigate to Azure Portal
-----------------------------
Go to https://portal.azure.com and sign in with your Azure account.
2. Open App Registrations
---------------------------
* In the Azure Portal, search for **"App registrations"** in the top search bar
* Click on **App registrations** service
3. Register New Application
-----------------------------
* Click **"+ New registration"** at the top
* Fill in the registration form:
**Name**
Enter a descriptive name, e.g., ``MEGDocs Microsoft Integration``
**Supported account types**
Select one of:
* **Accounts in any organizational directory (Any Azure AD directory - Multitenant)**
if you want to support users from any organization
* **Accounts in any organizational directory and personal Microsoft accounts**
if you also want to support personal OneDrive accounts
**Redirect URI**
* Platform: Select **Web**
* URI: Enter your callback URL:
.. code-block:: text
https://audits.megsupporttools.com/auth/oauth2/microsoft/callback/
.. note::
The callback url may be different if deploying an integration for a specific region.
* Click **Register**
Step 2: Configure API Permissions
===================================
1. Add Microsoft Graph Permissions
------------------------------------
* In your newly created app registration, click **"API permissions"** in the left sidebar
* Click **"+ Add a permission"**
* Select **"Microsoft Graph"**
* Choose **"Delegated permissions"**
* Search for and add the following permissions:
* ``User.Read`` - Read user profile
* ``Files.ReadWrite.All`` - Read and write all user files
* ``offline_access`` - Maintain access to data (for refresh tokens)
* Click **"Add permissions"**
2. Grant Admin Consent (Optional)
-----------------------------------
If your organization requires admin consent for these permissions:
* Click **"Grant admin consent for [Your Organization]"**
* Confirm the action
.. warning::
Admin consent may be required depending on your organization's Azure AD policies.
Contact your Azure administrator if you don't have permission to grant consent.
Step 3: Create Client Secret
==============================
1. Navigate to Certificates & Secrets
---------------------------------------
* In your app registration, click **"Certificates & secrets"** in the left sidebar
2. Create New Client Secret
-----------------------------
* Under **"Client secrets"**, click **"+ New client secret"**
* Fill in:
**Description**
Enter a description, e.g., ``MEGDocs Production Secret``
**Expires**
Select an expiration period:
* 6 months
* 12 months (recommended)
* 24 months
* Custom
* Click **"Add"**
3. Copy Client Secret
-----------------------
.. important::
**Copy the secret value immediately!**
The client secret value is only shown once. Copy it now and store it securely.
You'll need this value for the ``MICROSOFT_CLIENT_SECRET`` environment variable.
.. warning::
* Never commit client secrets to version control
* Store secrets in a secure secret management system
* Rotate secrets before they expire
Step 4: Get Application (Client) ID
=====================================
* In your app registration overview page, locate the **"Application (client) ID"**
* Copy this value - you'll need it for the ``MICROSOFT_CLIENT_ID`` environment variable
Step 5: Configure Environment Variables
=========================================
Set the following environment variables in your MEGDocs deployment:
.. code-block:: bash
# Microsoft Integration
MICROSOFT_CLIENT_ID=your-application-client-id-here
MICROSOFT_CLIENT_SECRET=your-client-secret-here
Replace the placeholder values with:
* ``your-application-client-id-here``: The Application (client) ID from Step 4
* ``your-client-secret-here``: The client secret value from Step 3
.. seealso::
See :ref:`setting env vars` for different methods of setting environment variables.
Step 6: Restart Application
=============================
After setting the environment variables, restart your MEGDocs application to load the new configuration:
**Docker Compose**
.. code-block:: bash
docker-compose restart cms
**Docker Stack**
.. code-block:: bash
docker service update --force megdocs_cms
**Kubernetes**
.. code-block:: bash
kubectl rollout restart deployment/megdocs-cms
Step 7: Test the Integration
==============================
1. Log in to MEGDocs
----------------------
* Log in as a test user
* Navigate to **Account Settings**
2. Connect Microsoft
---------------------
* Click on the **"Microsoft"** tab
* Click **"Connect to Microsoft"**
* You should be redirected to Microsoft login page
* Sign in with a Microsoft account
* Grant the requested permissions
* You should be redirected back to MEGDocs with "Connected successfully!" message
3. Verify Connection
---------------------
* Check that the Microsoft tab shows "Connected" status
* Note the token expiration time
* Verify in Django admin that the ``Oauth2Integration`` record was created
Troubleshooting
================
Error: "Redirect URI mismatch"
-------------------------------
**Problem**: Microsoft shows error about redirect URI not matching
**Solution**:
1. Check that the URI registered in Azure Portal matches the format `https://audits{SUBDOMAIN}.megsupportools.com/oauth2/microsoft/callback`
2. Ensure there are no trailing slashes or URL encoding issues
3. Verify the protocol (http vs https) matches
4. Add all necessary redirect URI variants in Azure Portal
Error: "Application not found"
-------------------------------
**Problem**: Error says application doesn't exist or is disabled
**Solution**:
1. Verify ``MICROSOFT_CLIENT_ID`` is correct
2. Check that the app registration is in the correct Azure tenant
3. Ensure the app registration hasn't been deleted
Error: "Invalid client secret"
-------------------------------
**Problem**: Token exchange fails with invalid client error
**Solution**:
1. Verify ``MICROSOFT_CLIENT_SECRET`` is correct
2. Check if the client secret has expired
3. Create a new client secret if needed
4. Ensure no extra spaces or line breaks in the secret value
Error: "Insufficient permissions"
----------------------------------
**Problem**: User can't access OneDrive files
**Solution**:
1. Verify all three permissions are added in Azure Portal:
* User.Read
* Files.ReadWrite.All
2. Check if admin consent is required and granted
3. Try disconnecting and reconnecting Microsoft
Local Development
==================
* serve the localhost:8000 port using ngrok:
.. code-block:: bash
ngrok http 8000
* In the app registration in the Azure Portal, add a redirect URI for the ngrok url. If using the free version of ngrok the url changes every time you run ngrok http.
.. code-block:: text
https://{SUBDOMAIN}.ngrok-free.app/auth/oauth2/microsoft/callback/
* Set the following environment variables
.. code-block:: bash
MICROSOFT_CLIENT_ID=your-dev-client-id
MICROSOFT_CLIENT_SECRET=your-dev-client-secret
MICROSOFT_OAUTH_CALLBACK_URL=https://{SUBDOMAIN}.ngrok-free.app/auth/oauth2/microsoft/callback/
CSRF_TRUSTED_ORIGINS=https://{SUBDOMAIN}.ngrok-free.app
Maintenance
============
Secret Rotation
----------------
When rotating client secrets:
1. Create a new client secret in Azure Portal (don't delete the old one yet)
2. Update ``MICROSOFT_CLIENT_SECRET`` environment variable
3. Restart application
4. Test that new connections work
5. Wait 24-48 hours for all active sessions to refresh tokens
6. Delete the old secret from Azure Portal
Monitoring
-----------
Monitor these metrics:
* **Failed OAuth attempts**: Check application logs for authentication errors
* **Token refresh failures**: Monitor for refresh token errors (indicates users need to reconnect)
* **Connection count**: Track number of active Microsoft integrations
* **API rate limits**: Monitor Microsoft Graph API usage
Additional Resources
=====================
* `Microsoft Identity Platform Documentation `_
* `Microsoft Graph API Reference `_
* `MSAL Python Library `_
* :doc:`/apps/meg-docs/microsoft-365-integration` - User and admin documentation