Sign out identityserver4 with identityserver3 library in mvc client

回眸只為那壹抹淺笑 提交于 2019-12-08 13:17:11

问题


I have a IdentityServer4 authentication server. I also have an ASP.NET MVC (.Net Framework 4.6) web client. I'm trying to sign out the user, using

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

It is then redirected to the authentication server account/logout view saying - You are now logged out. Click here to return to the client application.

After clicking the logout redirect, I am redirected to my page where I can click sign-in again. After clicking sign-in, i am automatically signed-in. Seems that sign-out does not work. What am I missing? Thank you

updated: Identity Server 4 logs below

[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) Logout code:

[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 Logout (from sample codes)

[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);
    }

Client Configuration:

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:


Try this:

  1. In your client (the MVC app), in the startup, where configuring the OpenIdConnectAuthenticationOptions, in the Notifications you should have:

    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. Then in your controllers - when you call the logout action (user clicks the logout button or whatever):

    public ActionResult Logout()
    {
        Request.GetOwinContext().Authentication.SignOut();
        return Redirect("/");
    }
    
  3. Then, when configuring your client on the IdentityServer side, the PostLogoutRedirectUris are up to you, but they are not the signout call back. This should be some page in your client (anonymous allowed), that says that the user is logged out or something like this (up to you). The important property is FrontChannelLogoutUri which you should set to call this:

    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");
        }
    }
    

You can also use BackChannelLogoutUri - depending on your clients, check here.

My guess is that your step 2 is fine, and you need to tweak the things around steps 1 and 3, but start from step 1. This is the step that says to IdentityServer to logout the user, by sending the ID token.

I hope that this helps.



来源:https://stackoverflow.com/questions/48365146/sign-out-identityserver4-with-identityserver3-library-in-mvc-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!