| name | msal-auth-code-flow |
| description | Authorization Code Flow for web applications using MSAL.NET confidential client to sign in users and access APIs on their behalf |
| tags | ["msal","auth-code","authorization-code","web-app","confidential-client","user-sign-in","redirect","consent"] |
Authorization Code Flow Skill
Overview
Authorization Code Flow is used by web applications to authenticate users and obtain access tokens on their behalf.
When to Use
- Web applications with server-side backend
- Need to access user-scoped APIs
- User sign-in required
- Refresh tokens needed
Flow Steps
- Redirect user to AAD login page
- User logs in and consents to permissions
- AAD returns authorization code to callback URL
- Server exchanges code for token using confidential credentials
- Token cached and used to access APIs
Agent Actions
Generate Code Snippet
Agent can show code snippets for each credential type:
Setup Guidance
Reference appropriate credential setup:
Example: Web Application with Certificate
[HttpGet("auth/callback")]
public async Task HandleCallback(string code, string state)
{
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithCertificate(cert)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}/v2.0")
.WithRedirectUri("https://myapp.com/auth/callback")
.Build();
var result = await app.AcquireTokenByAuthorizationCode(
new[] { "scope-uri" },
code)
.ExecuteAsync();
}
Error Resolution
Refer to Troubleshooting Guide
Best Practices
Explain the Flow
- Initiation: Redirect to
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id=...&redirect_uri=...
- User Action: User logs in and grants consent
- Code Reception: AAD sends authorization code to redirect URI
- Token Exchange: Server uses code + client credentials to get token
- Token Usage: Token cached and used for API calls
Decision Help
Choose Auth Code Flow if:
- Building web application with server backend
- Need to access user resources with user consent
- Want to maintain long-lived sessions (using refresh tokens)
Avoid if:
- Building single-page app (use implicit/hybrid instead)
- Don't have secure backend for credentials