在Docker中运行AzureAD认证ASP.NET Core MVC应用报错
Fixes for AzureAD Auth Errors in Dockerized ASP.NET Core MVC App
1. Resolve "Correlation failed." Error
This error typically stems from mismatched request context between the external client and the containerized app.
- Configure Forward Headers: Since Docker forwards requests from port 8080 to port 80 inside the container, the app needs to recognize the external host/port. Add this middleware in
Program.cs(before authentication middleware):app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); - Validate AzureAD Redirect URI: Ensure the redirect URI in your AzureAD app registration exactly matches
http://localhost:8080/signin-oidc(include the correct scheme, no trailing slashes). Double-check thatClientIdandTenantIdinappsettings.jsonmatch AzureAD values. - Update Allowed Hosts: In
appsettings.json, set"AllowedHosts": "*"(or specific hosts) to avoid blocking localhost requests.
2. Fix "Unable to unprotect the message.State." Error
This issue relates to lost data protection keys when containers restart. By default, ASP.NET Core uses an in-memory key ring that doesn't persist across container runs.
- Persist Data Protection Keys: For local testing, mount a volume to store keys outside the container. Add this to your
docker runcommand:
Then configure data protection in-v ${HOME}/aspnet-dataprotection:/var/aspnet/DataProtection-KeysProgram.csto use this directory:builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo("/var/aspnet/DataProtection-Keys")) .SetApplicationName("YourAppName"); // Use your actual app name - Adjust Cookie Policy Settings: Ensure cookie policy aligns with AzureAD's requirements. Configure this in
Program.cs:
Placebuilder.Services.Configure<CookiePolicyOptions>(options => { options.MinimumSameSitePolicy = SameSiteMode.Unspecified; options.OnAppendCookie = ctx => ctx.CookieOptions.SameSite = SameSiteMode.None; options.OnDeleteCookie = ctx => ctx.CookieOptions.SameSite = SameSiteMode.None; options.Secure = CookieSecurePolicy.None; // Use "Always" in production with HTTPS });app.UseCookiePolicy();beforeapp.UseAuthentication();andapp.UseAuthorization();.
3. Additional Troubleshooting Steps
- Clear Browser Cookies: Old auth cookies from previous runs can cause conflicts. Delete all localhost-related cookies before retesting.
- Enable Detailed Logging: In
appsettings.json, set verbose logging to debug auth flow issues:"Logging": { "LogLevel": { "Microsoft.AspNetCore.Authentication": "Debug", "Microsoft": "Information" } } - Check Container Network Access: Verify the container can reach AzureAD by running
curl https://login.microsoftonline.cominside the container.
内容的提问来源于stack exchange,提问作者Kyle Barnes
相关产品推荐
相关产品推荐

