简体   繁体   中英

How To logout user with ajax in identityserver3

I configed my identityserver project to skip logout page.It shows logout page for one or two second.But i set PostSignOutAutoRedirectDelay=0 so i want logout user with ajax.But i get: Response for preflight has invalid HTTP status code 405. And my log file says:

2018-02-07 11:49:40.475 +03:30 [Information] End authorize request
2018-02-07 11:49:40.479 +03:30 [Information] Posting to 
http://localhost:14600/
2018-02-07 11:49:40.480 +03:30 [Debug] Using DefaultViewService to render 
authorization response HTML
2018-02-07 11:49:57.949 +03:30 [Information] CORS request made for path: 
"/connect/endsession" from origin: "http://localhost:14600" but rejected 
because invalid CORS path

Here is my client class code:

And my startup class:

    public void Configuration(IAppBuilder app)
    {

        app.Map("/identity", idsrvApp =>
        {
            var factory =
                new IdentityServerServiceFactory().UseInMemoryClients(Clients.Get())
                                                  .UseInMemoryScopes(Scopes.Get())
                                                  .UseInMemoryUsers(Users.Get());

            var userService = new UserService();


            factory.UserService = new Registration<IUserService>(reslove => userService);
            var viewOptions = new DefaultViewServiceOptions();
            viewOptions.CacheViews = false;
            factory.ConfigureDefaultViewService(viewOptions);
            var options = new IdentityServerOptions
            {
                SigningCertificate = LoadCertificate(),

                Factory = factory,
                Endpoints = new EndpointOptions()
                {
                    EnableCspReportEndpoint = true,
                    EnableAuthorizeEndpoint = true,
                    EnableTokenRevocationEndpoint = true,
                    EnableEndSessionEndpoint = true,
                    EnableCheckSessionEndpoint = true,
                    EnableUserInfoEndpoint = true,
                    EnableDiscoveryEndpoint = true,
                    EnableTokenEndpoint = true,
                    EnableIdentityTokenValidationEndpoint = true,
                    EnableClientPermissionsEndpoint = true,
                    EnableAccessTokenValidationEndpoint = true,
                    EnableIntrospectionEndpoint = true
                },
                AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                {
                    //sign out with out confirm
                    EnablePostSignOutAutoRedirect = true,
                    EnableSignOutPrompt = false,
                    PostSignOutAutoRedirectDelay=0


                    //   IdentityProviders = ConfigureAdditionalIdentityProviders,
                }
            };

            idsrvApp.UseIdentityServer(options);
        });

        string ss = HttpContext.Current.Server.MapPath("~/Content/identity.log");
        Serilog.Log.Logger =
            new LoggerConfiguration().MinimumLevel.Debug()
                .WriteTo.RollingFile(pathFormat: ss)
                .CreateLogger();
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });


        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            Authority = ConfigurationManager.AppSettings["Authority"],

            ClientId = "Identity",
            Scope = "openid profile roles sampleApi",
            ResponseType = "id_token token",
            RedirectUri = ConfigurationManager.AppSettings["RedirectUri"],

            SignInAsAuthenticationType = "Cookies",
            UseTokenLifetime = false,
            PostLogoutRedirectUri= "https://www.google.com",
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = async n =>
                {
                    var nid = new ClaimsIdentity(
                        n.AuthenticationTicket.Identity.AuthenticationType,
                        Constants.ClaimTypes.GivenName,
                        Constants.ClaimTypes.Role);
                    // get userinfo data
                    var userInfoClient = new UserInfoClient(
                        new Uri(n.Options.Authority + "/connect/userinfo"),
                        n.ProtocolMessage.AccessToken);

                    var userInfo = await userInfoClient.GetAsync();
                    userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                    // keep the id_token for logout
                    nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                    // add access token for sample API
                    nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                    // keep track of access token expiration
                    nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                    // add some other app specific claim
                    nid.AddClaim(new Claim("app_specific", "some data"));

                    n.AuthenticationTicket = new AuthenticationTicket(
                        nid,
                        n.AuthenticationTicket.Properties);
                },

                RedirectToIdentityProvider = n =>
                {
                    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);
                }
            }
        });
    }

And my action:

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

IdentityServer 3 (and 4) is an implementation of OpenID Connect and some of its extensions that currently implementer's draft. In OpenID Connect there is no way to issue a logout request via ajax. You have two ways to logout...assuming you're using the front-channel (user agent):

  • clear your application session, this will log the user out of the current application (RP), not the openid provider
  • Issue a request to end session endpoint and have your application listen for logout logout request on a pre-configured logout url to clear local session. This will log you out of all applications

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM