Azure App Service上Duende ASP.NET Identity外部登录报错求助
Duende ASP.NET Identity 外部登录(Microsoft)在Azure App Service部署后出现重定向错误
问题现象
- 部署在Azure App Service的Duende ASP.NET Identity项目,使用Microsoft外部提供商登录时出现错误:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. - 页面停留在URL:
https://{App service name}.azurewebsites.net/signin-microsoft?code={randomcode} - 本地运行正常,仅Azure环境出现该问题
认证代码
builder.Services.AddAuthentication(options => { options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultSignInScheme = IdentityConstants.ExternalScheme; }) .AddMicrosoftAccount(options => { options.ClientId = aadConfig.ClientId; options.ClientSecret = aadConfig.ClientSecret; options.AuthorizationEndpoint = aadConfig.AuthorityEndpoint; options.TokenEndpoint = aadConfig.TokenEndpoint; }) .AddJwtBearer(options => { options.Authority = addressConfig.AuthorityAddress; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuers = validIssuers, ValidateAudience = false }; }) .AddIdentityCookies(options => { options.ApplicationCookie.PostConfigure(identityCookieOptions => { identityCookieOptions.ExpireTimeSpan = TimeSpan.FromDays(30); }); options.TwoFactorRememberMeCookie.PostConfigure(twoFactorCookieOptions => { twoFactorCookieOptions.ExpireTimeSpan = TimeSpan.FromDays(30); }); });
已完成配置
- 已在Azure应用注册中添加Web平台重定向URI:
https://{App service name}.azurewebsites.net/signin-microsoft - 调试发现流程进入
Account/PerformExternalLogin,但无法跳转到ExternalLogin.razor页面,登录后无法重定向到预期页面
排查步骤
配置ForwardedHeaders中间件
Azure App Service通过X-Forwarded-For/X-Forwarded-Proto传递原始请求信息,需在UseAuthentication和UseAuthorization之前添加:app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto });同时确保App Service启用强制HTTPS。
验证Microsoft Account端点配置
- 确认
aadConfig.AuthorityEndpoint和aadConfig.TokenEndpoint为Azure AD有效端点(若无特殊需求,可移除手动指定,使用AddMicrosoftAccount默认公共端点) - 核对ClientId和ClientSecret与Azure应用注册中的值完全一致,无多余空格或特殊字符
- 确认
检查路由与页面逻辑
- 确认
ExternalLogin.razor页面路由配置正确,无路由冲突 - 检查
Account/PerformExternalLogin动作的返回逻辑,确保正确重定向到ExternalLogin页面
- 确认
开启详细日志排查
- 在App Service中开启应用日志和详细错误日志,查看具体错误信息
- 配置日志级别为Debug获取认证中间件细节:
"Logging": { "LogLevel": { "Microsoft.AspNetCore.Authentication": "Debug", "Microsoft.AspNetCore.Identity": "Debug" } }
调整Cookie安全配置
针对Azure环境调整Cookie的SameSite和Secure属性:options.ApplicationCookie.PostConfigure(identityCookieOptions => { identityCookieOptions.ExpireTimeSpan = TimeSpan.FromDays(30); identityCookieOptions.SameSite = SameSiteMode.Lax; identityCookieOptions.SecurePolicy = CookieSecurePolicy.Always; });
内容的提问来源于stack exchange,提问作者Richard Vo
相关产品推荐
相关产品推荐

