在 mvc 客户端中使用 identityserver3 库注销 identityserver4

Sign out identityserver4 with identityserver3 library in mvc client

我有一个 IdentityServer4 身份验证服务器。我还有一个 ASP.NET MVC (.Net Framework 4.6) 网络客户端。我正在尝试注销用户,使用

Request.GetOwinContext().Authentication.SignOut();

然后重定向到认证服务器account/logout查看说- 您现在已注销。点击此处return到客户端申请。

点击注销重定向后,我被重定向到我可以再次点击登录的页面。单击登录后,我将自动登录。似乎注销不起作用。我错过了什么?谢谢

更新: Identity Server 4 日志如下

[02:41:07 Debug] IdentityServer4.Services.DefaultClaimsService Getting claims for access token for client: dpcdwebclient

[02:41:07 Debug] IdentityServer4.Services.DefaultClaimsService Getting claims for access token for client: dpcdwebclient

[02:41:07 Debug] IdentityServer4.Endpoints.TokenEndpoint Token request success.

[02:41:07 Debug] IdentityServer4.Endpoints.TokenEndpoint Token request success.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Debug] IdentityServer4.Hosting.EndpointRouter Request path /connect/endsession matched to endpoint type Endsession

[02:41:10 Debug] IdentityServer4.Hosting.EndpointRouter Request path /connect/endsession matched to endpoint type Endsession

[02:41:10 Debug] IdentityServer4.Hosting.EndpointRouter Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionEndpoint

[02:41:10 Debug] IdentityServer4.Hosting.EndpointRouter Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionEndpoint

[02:41:10 Information] IdentityServer4.Hosting.IdentityServerMiddleware Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionEndpoint for /connect/endsession

[02:41:10 Information] IdentityServer4.Hosting.IdentityServerMiddleware Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionEndpoint for /connect/endsession

[02:41:10 Debug] IdentityServer4.Endpoints.EndSessionEndpoint Processing signout request for cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df

[02:41:10 Debug] IdentityServer4.Endpoints.EndSessionEndpoint Processing signout request for cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df

[02:41:10 Debug] IdentityServer4.Validation.EndSessionRequestValidator Start end session request validation

[02:41:10 Debug] IdentityServer4.Validation.EndSessionRequestValidator Start end session request validation

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Start identity token validation

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Start identity token validation

[02:41:10 Debug] IdentityServer4.EntityFramework.Stores.ClientStore dpcdwebclient found in database: True

[02:41:10 Debug] IdentityServer4.EntityFramework.Stores.ClientStore dpcdwebclient found in database: True

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Client found: dpcdwebclient / DPCD Web Client

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Client found: dpcdwebclient / DPCD Web Client

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Calling into custom token validator: IdentityServer4.Validation.DefaultCustomTokenValidator

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Calling into custom token validator: IdentityServer4.Validation.DefaultCustomTokenValidator

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Token validation success { "ClientId": "dpcdwebclient", "ClientName": "DPCD Web Client", "ValidateLifetime": false, "Claims": { "nbf": 1516560060, "exp": 1516560360, "iss": "http://localhost:9000", "aud": "dpcdwebclient", "nonce": "636521568596713051.ZGU2MmM3YzMtMjI5Yi00YmFlLThhMzUtOTBjM2U2NWIwZjhjZThmZmNkN2EtNmFlYS00NjZiLWExMWMtNjY3YjEzYmM4YzY5", "iat": 1516560060, "c_hash": "OOI3bdt6NUGB4bptfc9w_A", "sid": "5caef14630a16f452d9b0bfe03906fe5", "sub": "cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df", "auth_time": 1516559499, "idp": "local", "amr": "pwd" } }

[02:41:10 Debug] IdentityServer4.Validation.TokenValidator Token validation success { "ClientId": "dpcdwebclient", "ClientName": "DPCD Web Client", "ValidateLifetime": false, "Claims": { "nbf": 1516560060, "exp": 1516560360, "iss": "http://localhost:9000", "aud": "dpcdwebclient", "nonce": "636521568596713051.ZGU2MmM3YzMtMjI5Yi00YmFlLThhMzUtOTBjM2U2NWIwZjhjZThmZmNkN2EtNmFlYS00NjZiLWExMWMtNjY3YjEzYmM4YzY5", "iat": 1516560060, "c_hash": "OOI3bdt6NUGB4bptfc9w_A", "sid": "5caef14630a16f452d9b0bfe03906fe5", "sub": "cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df", "auth_time": 1516559499, "idp": "local", "amr": "pwd" } }

[02:41:10 Information] IdentityServer4.Validation.EndSessionRequestValidator End session request validation success { "ClientId": "dpcdwebclient",
"ClientName": "DPCD Web Client", "SubjectId": "cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df", "PostLogOutUri": "http://localhost:9002/signout-callback-oidc", "Raw": { "id_token_hint": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdmMjM1MDRjNjc3NzkzM2I0MDU5ODU5ZDA4MTMzOGMyIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MTY1NjAwNjAsImV4cCI6MTUxNjU2MDM2MCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo5MDAwIiwiYXVkIjoiZHBjZHdlYmNsaWVudCIsIm5vbmNlIjoiNjM2NTIxNTY4NTk2NzEzMDUxLlpHVTJNbU0zWXpNdE1qSTVZaTAwWW1GbExUaGhNelV0T1RCak0yVTJOV0l3WmpoalpUaG1abU5rTjJFdE5tRmxZUzAwTmpaaUxXRXhNV010TmpZM1lqRXpZbU00WXpZNSIsImlhdCI6MTUxNjU2MDA2MCwiY19oYXNoIjoiT09JM2JkdDZOVUdCNGJwdGZjOXdfQSIsInNpZCI6IjVjYWVmMTQ2MzBhMTZmNDUyZDliMGJmZTAzOTA2ZmU1Iiwic3ViIjoiY2M1YTJkOGMtNzdkOS00NzdkLThlZWQtNDhiOGNiN2NjOGRmIiwiYXV0aF90aW1lIjoxNTE2NTU5NDk5LCJpZHAiOiJsb2NhbCIsImFtciI6WyJwd2QiXX0.P7Zn6GVdSuUaFS55DGqjA2PlRYH0CLIHPI7AKtOnNYn24sTagOBlX57Fg_QVmCczLrkdIwh-Deok2bXjf3O5ZrYKWN3OFKqkDx0CfTN3zypxruiumWEdhqtK_13iinh2n1XLiV0OeUozOCMsDVI2hMTcnHQxsIGlQigETeoRaG6NlB5jGB5-3i7DCJycywPyWV-CcMLJkEiAunLbVXGOsdALQxZTYFsXlffQA4vRybAK6d5Ybc5139vjW68jV4Rbjm9ihhFv4edwALcEYPICBWLR0FxGLWd6XOH56rK7HCoiom4v8afgFimS4MhfyEIkuKu0md46XrBF2MYy3xtdOQ", "x-client-SKU": "ID_NET", "x-client-ver": "1.0.40306.1554" } }

[02:41:10 Information] IdentityServer4.Validation.EndSessionRequestValidator End session request validation success { "ClientId": "dpcdwebclient",
"ClientName": "DPCD Web Client", "SubjectId": "cc5a2d8c-77d9-477d-8eed-48b8cb7cc8df", "PostLogOutUri": "http://localhost:9002/signout-callback-oidc", "Raw": { "id_token_hint": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjdmMjM1MDRjNjc3NzkzM2I0MDU5ODU5ZDA4MTMzOGMyIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MTY1NjAwNjAsImV4cCI6MTUxNjU2MDM2MCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo5MDAwIiwiYXVkIjoiZHBjZHdlYmNsaWVudCIsIm5vbmNlIjoiNjM2NTIxNTY4NTk2NzEzMDUxLlpHVTJNbU0zWXpNdE1qSTVZaTAwWW1GbExUaGhNelV0T1RCak0yVTJOV0l3WmpoalpUaG1abU5rTjJFdE5tRmxZUzAwTmpaaUxXRXhNV010TmpZM1lqRXpZbU00WXpZNSIsImlhdCI6MTUxNjU2MDA2MCwiY19oYXNoIjoiT09JM2JkdDZOVUdCNGJwdGZjOXdfQSIsInNpZCI6IjVjYWVmMTQ2MzBhMTZmNDUyZDliMGJmZTAzOTA2ZmU1Iiwic3ViIjoiY2M1YTJkOGMtNzdkOS00NzdkLThlZWQtNDhiOGNiN2NjOGRmIiwiYXV0aF90aW1lIjoxNTE2NTU5NDk5LCJpZHAiOiJsb2NhbCIsImFtciI6WyJwd2QiXX0.P7Zn6GVdSuUaFS55DGqjA2PlRYH0CLIHPI7AKtOnNYn24sTagOBlX57Fg_QVmCczLrkdIwh-Deok2bXjf3O5ZrYKWN3OFKqkDx0CfTN3zypxruiumWEdhqtK_13iinh2n1XLiV0OeUozOCMsDVI2hMTcnHQxsIGlQigETeoRaG6NlB5jGB5-3i7DCJycywPyWV-CcMLJkEiAunLbVXGOsdALQxZTYFsXlffQA4vRybAK6d5Ybc5139vjW68jV4Rbjm9ihhFv4edwALcEYPICBWLR0FxGLWd6XOH56rK7HCoiom4v8afgFimS4MhfyEIkuKu0md46XrBF2MYy3xtdOQ", "x-client-SKU": "ID_NET", "x-client-ver": "1.0.40306.1554" } }

[02:41:10 Debug] IdentityServer4.Endpoints.EndSessionEndpoint Success validating end session request from dpcdwebclient

[02:41:10 Debug] IdentityServer4.Endpoints.EndSessionEndpoint Success validating end session request from dpcdwebclient

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:10 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.External signed out.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.External signed out.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:12 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler AuthenticationScheme: Identity.Application was successfully authenticated.

[02:41:12 Debug] IdentityServer4.Hosting.EndpointRouter Request path /connect/endsession/callback matched to endpoint type Endsession

[02:41:12 Debug] IdentityServer4.Hosting.EndpointRouter Request path /connect/endsession/callback matched to endpoint type Endsession

[02:41:12 Debug] IdentityServer4.Hosting.EndpointRouter Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionCallbackEndpoint

[02:41:12 Debug] IdentityServer4.Hosting.EndpointRouter Endpoint enabled: Endsession, successfully created handler: IdentityServer4.Endpoints.EndSessionCallbackEndpoint

[02:41:12 Information] IdentityServer4.Hosting.IdentityServerMiddleware Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionCallbackEndpoint for /connect/endsession/callback

[02:41:12 Information] IdentityServer4.Hosting.IdentityServerMiddleware Invoking IdentityServer endpoint: IdentityServer4.Endpoints.EndSessionCallbackEndpoint for /connect/endsession/callback

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint Processing signout callback request

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint Processing signout callback request

[02:41:12 Debug] IdentityServer4.EntityFramework.Stores.ClientStore dpcdwebclient found in database: True

[02:41:12 Debug] IdentityServer4.EntityFramework.Stores.ClientStore dpcdwebclient found in database: True

[02:41:12 Debug] IdentityServer4.Validation.EndSessionRequestValidator No client front-channel logout URLs

[02:41:12 Debug] IdentityServer4.Validation.EndSessionRequestValidator No client front-channel logout URLs

[02:41:12 Debug] IdentityServer4.Validation.EndSessionRequestValidator No client back-channel logout URLs

[02:41:12 Debug] IdentityServer4.Validation.EndSessionRequestValidator No client back-channel logout URLs

[02:41:12 Information] IdentityServer4.Endpoints.EndSessionCallbackEndpoint Successful signout callback.

[02:41:12 Information] IdentityServer4.Endpoints.EndSessionCallbackEndpoint Successful signout callback.

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint No client front-channel iframe urls

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint No client front-channel iframe urls

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint No client back-channel iframe urls

[02:41:12 Debug] IdentityServer4.Endpoints.EndSessionCallbackEndpoint No client back-channel iframe urls

ASP.NET MVC 5 (Identity Server 3) 注销代码:

[HttpGet]
    public ActionResult SignOut()
    {
        Request.GetOwinContext().Authentication.SignOut();
        return Redirect("/");
    }

    //signout-oidc redirect
    [AllowAnonymous]
    public ActionResult LogoutCallback()
    {
        Request.GetOwinContext().Authentication.SignOut("Cookies");
        return RedirectToAction("Index", "Home");
    }

IDS4 注销(来自示例代码)

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout(LogoutInputModel model)
    {
        // build a model so the logged out page knows what to display
        var vm = await _account.BuildLoggedOutViewModelAsync(model.LogoutId);

        var user = HttpContext.User;
        if (user?.Identity.IsAuthenticated == true)
        {
            // delete local authentication cookie
            await HttpContext.SignOutAsync();

            // raise the logout event
            await _events.RaiseAsync(new UserLogoutSuccessEvent(user.GetSubjectId(), user.GetDisplayName()));
        }

        // check if we need to trigger sign-out at an upstream identity provider
        if (vm.TriggerExternalSignout)
        {
            // build a return URL so the upstream provider will redirect back
            // to us after the user has logged out. this allows us to then
            // complete our single sign-out processing.
            string url = Url.Action("Logout", new { logoutId = vm.LogoutId });

            // this triggers a redirect to the external provider for sign-out
            return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
        }

        return View("LoggedOut", vm);
    }

客户端配置:

new Client
            {
                ClientId = "dpcdwebclient",
                ClientName = "DPCD Web Client",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                Enabled = true,

                RequireConsent = false,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },

                RedirectUris = { "http://localhost:9002/signin-oidc" },
                PostLogoutRedirectUris = { "http://localhost:9002/signout-callback-oidc" },

                AlwaysIncludeUserClaimsInIdToken = true,

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.OfflineAccess,
                    "myapi"
                },

                AllowOfflineAccess = true
            },

试试这个:

  1. 在您的客户端(MVC 应用程序)中,在启动时配置 OpenIdConnectAuthenticationOptions,在 Notifications 中您应该有:

    RedirectToIdentityProvider = n =>
                {
                    // if signing out, add the id_token_hint
                    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                    {
                        var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
    
                        if (idTokenHint != null)
                        {
                            n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                        }
    
                    }
                    return Task.FromResult(0);
                },
    
  2. 然后在您的控制器中 - 当您调用注销操作时(用户单击注销按钮或其他):

    public ActionResult Logout()
    {
        Request.GetOwinContext().Authentication.SignOut();
        return Redirect("/");
    }
    
  3. 然后,在 IdentityServer 端配置您的客户端时,PostLogoutRedirectUris 由您决定,但它们不是注销回调。这应该是您客户端中的某个页面(允许匿名),表示用户已注销或类似的内容(由您决定)。重要的 属性 是 FrontChannelLogoutUri 你应该设置为调用这个:

    public void SignoutCleanup(string sid)
    {
        var cp = (ClaimsPrincipal)User;
        var sidClaim = cp.FindFirst("sid");
        if (sidClaim != null && sidClaim.Value == sid)
        {
            Request.GetOwinContext().Authentication.SignOut("Cookies");
        }
    }
    

您也可以使用 BackChannelLogoutUri - 根据您的客户,勾选 here

我猜你的第 2 步没问题,你需要调整第 1 步和第 3 步的内容,但是从第 1 步开始。这是告诉 IdentityServer 注销用户的步骤,方法是发送ID 令牌。

希望对您有所帮助。