ASP.NET Core集成Keycloak OpenIDConnect登出未跳转至登录页问题
ASP.NET Core 集成Keycloak OpenIDConnect 登出跳转异常问题
登录功能正常,但执行登出操作后,页面跳转到Web应用首页,而非预期的Keycloak登录页。以下是相关代码:
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { // 将会话存储到Cookie options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // 使用OpenId进行认证挑战 options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie(cookie => { cookie.Cookie.Name = "keycloak.cookie"; cookie.Cookie.MaxAge = TimeSpan.FromMinutes(60); cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; cookie.SlidingExpiration = true; }) .AddOpenIdConnect(options => { options.Authority = Configuration.GetSection("Keycloak")["Authority"]; // Keycloak客户端ID options.ClientId = Configuration.GetSection("Keycloak")["ClientId"]; // Keycloak客户端密钥 options.ClientSecret = Configuration.GetSection("Keycloak")["ClientSecret"]; // 测试环境禁用HTTPS(生产环境需设为true) options.RequireHttpsMetadata = false; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; // 使用的OpenID流程 options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.Events.OnSignedOutCallbackRedirect += context => { context.Response.Redirect(context.Options.SignedOutRedirectUri); context.HandleResponse(); return Task.CompletedTask; }; }); }
Index.cshtml
<a class="nav-link text-light" asp-page-handler="Logout" asp-page="/Pages/Index">Sign out</a>
Index.cshtml.cs
public IActionResult Logout() { return new SignOutResult( new[] { OpenIdConnectDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme }); }
解决方案
- 配置正确的登出后跳转地址
在AddOpenIdConnect配置中,添加SignedOutRedirectUri,指向Keycloak的登录页面(替换你的Realm名称为实际Keycloak领域名):
options.SignedOutRedirectUri = $"{options.Authority}/realms/你的Realm名称/protocol/openid-connect/auth";
移除或调整自定义登出回调事件
当前自定义的OnSignedOutCallbackRedirect事件强制跳转到SignedOutRedirectUri,但如果该Uri未配置,就会默认跳转到应用首页。如果不需要自定义逻辑,直接移除这段事件代码,框架会自动处理登出后的跳转;如果需要保留自定义逻辑,确保SignedOutRedirectUri已正确配置。确保登出操作同时清除Cookie和Keycloak会话
当前SignOutResult中已包含两个认证Scheme,这部分是正确的,确保了同时清除本地Cookie和向Keycloak发起登出请求。
内容的提问来源于stack exchange,提问作者SoftwareDveloper
相关产品推荐
相关产品推荐

