簡體   English   中英

如何在IdentityServer3中使用Ajax注銷用戶

[英]How To logout user with ajax in identityserver3

我將Identityserver項目配置為跳過注銷頁面。它顯示注銷頁面一到兩秒鍾。但是我設置了PostSignOutAutoRedirectDelay = 0,所以我希望使用ajax注銷用戶。但是我得到:預檢響應的HTTP狀態代碼為405無效。日志文件說:

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

這是我的客戶類代碼:

而我的啟動班:

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

我的行動:

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

IdentityServer 3(和4)是OpenID Connect及其當前實施者草案的某些擴展的實現。 在OpenID Connect中,無法通過ajax發出注銷請求。 您有兩種注銷方法……假設您使用的是前渠道(用戶代理):

  • 清除您的應用程序會話,這將使用戶退出當前應用程序(RP),而不是openid提供程序
  • 發出結束會話端點的請求,並讓您的應用程序偵聽預先配置的注銷URL上的注銷注銷請求,以清除本地會話。 這將使您退出所有應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM