从不使用 IdentityServer4 的 OIDC 客户端注销

时间:2021-05-08 18:40:55

标签: c# identityserver4 openid-connect .net-5 pkce

我目前正在使用 IdentityServer4 开发 .NET 5 应用程序。

我使用授权码 + PKCE 流程登录 - 不幸的是,注销似乎无法在本地主机上正常工作

我的应用程序环境如下:

  • 应用(WebApp)
  • IdentityServer4

IdentityServer4 中我的客户端定义如下所示:

// Authorization Code + PKCE Flow
new Client
{
    ClientId = "oidcClient",
    ClientName = "Example App",
    ClientSecrets = { new Secret("secret".Sha256()) },

    RedirectUris = { "https://localhost:44301/signin-oidc" },
    PostLogoutRedirectUris = { "https://localhost:44301/signout-callback-oidc" },

    AllowedGrantTypes = GrantTypes.Code,
    RequirePkce = true,
    RequireClientSecret = true,
    
    AllowedScopes = 
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        IdentityServerConstants.StandardScopes.Email,
        IdentityServerConstants.StandardScopes.OfflineAccess,
        "roles",
    },

    AllowPlainTextPkce = false,
},

我在客户端应用上的 OIDC 连接如下所示:

services.AddAuthentication(options => 
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => 
{
    options.Authority = "https://localhost:5001";
    options.RequireHttpsMetadata = true;
    options.ClientId = "oidcClient";
    options.ClientSecret = "secret";

    options.ResponseType = "code";
    options.UsePkce = true;
    options.ResponseMode = "query";

    options.Scope.Add("offline_access");
    options.Scope.Add("roles");
    
    options.SaveTokens = true;
});

我的 WebApp HomeController 中的注销方法如下所示:

public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

    return new SignOutResult(new[] { OpenIdConnectDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme });
}

IdentityServer4 日志告诉我登录 => 登录成功和注销 => 注销成功。

这很奇怪 - 应用程序一直保持登录状态。

当我退出并返回到 WebApp 主页索引页面时,我仍然处于登录状态 - 尽管我应该退出。

您知道如何在 IdentityServer4 OIDC 应用程序中正确配置注销吗?

你知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

Logout 方法不应返回任何内容。因为如果这样做,您将覆盖 SignOut 方法在内部生成的重定向。

更好的方法是:

public async Task DoLogout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
}