Minimal FastAPI service that demonstrates user sign‑in with Azure Active Directory (MSAL) and a call to Microsoft Graph
/v1.0/me.
- OAuth2 Authorization Code Flow via MSAL (Confidential Client)
- Fetch basic user profile from Microsoft Graph
- CORS configured via environment variable
ALLOWED_ORIGINS
- Python 3.11+
- Azure AD App Registration with a client secret
- Create an App Registration (type: Web) in Azure AD.
- Add Redirect URI:
http://localhost:8000/auth/callback. - Add Microsoft Graph delegated permission:
User.Read(grant admin consent if required). - Create a client secret and copy its Value.
Create a .env file in the project root:
AZURE_CLIENT_ID=your-app-client-id
AZURE_CLIENT_SECRET=your-app-client-secret
AZURE_TENANT_ID=your-tenant-id
REDIRECT_URI=http://localhost:8000/auth/callback
ALLOWED_ORIGINS=http://localhost:4200
Windows PowerShell:
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
macOS/Linux:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
uvicorn app.main:app --reload
Open API docs: http://localhost:8000/docs
GET /auth/login– starts the Azure AD login flow and returns anauth_urlfor redirect.GET /auth/callback– handles redirect from Azure AD, exchanges code for token, then calls Graph/meand returns a greeting.GET /test– simple CORS check endpoint.
- Start the app and open
http://localhost:8000/docs. - Call
GET /auth/login(or via browser) and copy theauth_url. - Open the
auth_urlin the browser, sign in/consent. - Azure redirects to
/auth/callbackand the API returns a short greeting.
- Client hits
/auth/loginand is redirected to Azure AD authorization page. - After consent/sign‑in, Azure AD redirects to
REDIRECT_URI(/auth/callback). - Backend exchanges the authorization code for an access token via MSAL.
- Backend calls Microsoft Graph
/v1.0/meand returns a short response with the display name.
- This is a learning/demo project. Authorization flow state is stored in memory and not suitable for production.
- Network call to Graph uses a small timeout and basic error handling.
- Keep secrets out of version control. Use environment variables/secret managers in real deployments.
- Error about missing env vars: check
.envvalues and names. - 400 at callback: ensure
REDIRECT_URIin Azure App matches exactly. - CORS errors in browser: update
ALLOWED_ORIGINSto include your frontend origin.