基于.NET Framework 4.5的Azure OpenID Connect Web应用认证状态不显示问题
问题描述
用户通过Azure完成认证后,页面自动重定向至首页,但应用未正确反映用户已认证状态,仍显示未登录状态。
相关配置信息
WebConfig 核心配置
<appSettings> <add key="ida:ClientId" value="[客户端ID]" /> <add key="ida:ADFSDiscoveryDoc" value="https://[ADFS域名]/adfs/.well-known/openid-configuration" /> <add key="ida:RedirectUri" value="https://localhost:44300/" /> </appSettings>
Startup.Auth 核心代码
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["ida:ClientId"], Authority = ConfigurationManager.AppSettings["ida:ADFSDiscoveryDoc"], RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"], ResponseType = OpenIdConnectResponseType.IdToken, Scope = OpenIdConnectScope.OpenIdProfile, UseTokenLifetime = false, Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = context => Task.FromResult(0), AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return Task.FromResult(0); } } }); }
AccountController 核心代码
public class AccountController : Controller { public void SignIn() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { HttpContext.GetOwinContext().Authentication.SignOut( CookieAuthenticationDefaults.AuthenticationType, OpenIdConnectAuthenticationDefaults.AuthenticationType); } }
登录后状态说明
首页仍显示“登录”按钮,未切换为用户信息或“退出”按钮,应用未识别到用户已完成认证。
排查与解决步骤
- 检查认证Cookie生成:打开浏览器开发者工具
Application标签,确认是否存在.AspNet.Cookies认证Cookie。若不存在,需核对UseCookieAuthentication与SetDefaultSignInAsAuthenticationType的AuthenticationType是否一致。 - 完善OpenID Connect响应处理:在
AuthorizationCodeReceived通知中添加调试逻辑,确认是否成功获取ID Token和用户信息。可将ResponseType改为OpenIdConnectResponseType.IdTokenToken,并扩展Scope为OpenIdConnectScope.OpenIdProfileEmail以获取完整用户数据。 - 确保用户身份持久化:在
AuthorizationCodeReceived中显式处理认证票据,将用户声明存入Cookie:AuthorizationCodeReceived = async context => { var claimsIdentity = context.AuthenticationTicket.Identity; claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.AuthenticationTicket.Identity.Name)); context.AuthenticationTicket = new AuthenticationTicket(claimsIdentity, context.AuthenticationTicket.Properties); } - 验证首页状态判断逻辑:确认首页视图中判断认证状态的代码正确,例如:
@if (User.Identity.IsAuthenticated) { <span>欢迎,@User.Identity.Name</span> <a href="/Account/SignOut">退出</a> } else { <a href="/Account/SignIn">登录</a> } - 核对Azure AD/ADFS配置:确保应用注册的
RedirectUri与WebConfig中的配置完全一致(含协议、域名、端口),且应用已被授予获取用户基本信息的权限。
内容的提问来源于stack exchange,提问作者Mark Riepe
相关产品推荐
相关产品推荐

