【问题标题】:Identity server 3 client with mvc and api not refreshing access token具有 mvc 和 api 的身份服务器 3 客户端不刷新访问令牌
【发布时间】:2017-03-21 01:51:51
【问题描述】:

我有一个有效的身份提供者。我设计用来对其进行身份验证的客户端是一个结合了 MVC 和 Web API 的单个项目。初始身份验证由 MVC 完成。如果访问令牌无效,它会按预期刷新。

MVC 端:

公共部分类启动{

    public void ConfigureAuth(IAppBuilder app)
    {
        //AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
        JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            CookieName = "CookieName",
            ReturnUrlParameter = "/Dashboard",
            LogoutPath = new PathString("/"),
        });
app.UseOpenIdConnectAuthentication(GetOpenIdConnectAuthenticationOptions());

    }


    private OpenIdConnectAuthenticationOptions GetOpenIdConnectAuthenticationOptions()
    {
        var options = new OpenIdConnectAuthenticationOptions
        {
            ClientId = "client.id",
            Authority = AuthorityUrl,
            RedirectUri = RedirectUri,
            PostLogoutRedirectUri = RedirectUri,
            ResponseType = "code id_token",
            Scope = "openid profile email offline_access roles company utc_offset service_api",

            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            },

            SignInAsAuthenticationType = "Cookies",
            Notifications = GetOpenIdConnectAuthenticationNotifications()
        };
        return options;
    }

    private OpenIdConnectAuthenticationNotifications GetOpenIdConnectAuthenticationNotifications()
    {
        var container = UnityLazyInit.Container;
        var authorizationProvider = container.Resolve<AuthorizationProvider>();
        var notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthorizationCodeReceived = async n =>
            {
                authorizationProvider.Authority = Authority;
                authorizationProvider.LoginMethod = LoginMethod;
                var tokenResponse = await authorizationProvider.GetAccessAndRefreshTokens(n);

                var userInfoClaims = await authorizationProvider.GetUserInfoClaims(tokenResponse);

                userInfoClaims = authorizationProvider.TransformUserInfoClaims(userInfoClaims);

                // create new identity
                var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                id.AddClaims(userInfoClaims);

                id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
                id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

                var user = authorizationProvider.GetUser(id);

                var applicationClaims = authorizationProvider.GetApplicationClaims(user);
                id.AddClaims(applicationClaims);

                var permisionClaims = authorizationProvider.GetPermisionClaims(user);
                id.AddClaims(permisionClaims);

                n.AuthenticationTicket = new AuthenticationTicket(
                    new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                    n.AuthenticationTicket.Properties);
            },

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

        };

        return notifications;
    }

}

表示层(浏览器端)利用了angulerjs,但是我没有加入任何对身份验证的支持。我依赖于 MVC。

当您的表示层调用 API 时,它会自动验证 MVC 检索到的访问令牌,但如果它过期,则无法刷新访问令牌。它也不会未经授权返回。它似乎正在尝试刷新但失败了。当 api 调用尝试刷新令牌时,演示文稿会收到身份提供者的错误页面的 HTML。

我该如何解决这个问题?在我看来,当 MVC 和 API 组合在一起时,它们应该自动进行身份验证和刷新,但这对我不起作用。

注意澄清上面的启动配置是共享的,但 MVC 和 API。

          new Client
            {
                ClientName = "MVC Client",
                ClientId = "client.id",
                ClientSecrets = new List<Secret> {
                    new Secret("secret".Sha256())
                },
                Flow = Flows.Hybrid,

                AllowedScopes = new List<string>

                {

                    Constants.StandardScopes.OpenId,

                    Constants.StandardScopes.Profile,

                    Constants.StandardScopes.Email,

                    Constants.StandardScopes.OfflineAccess,

                    "roles",

                    "company",

                    "utc_offset",

                    "service_api

" },

                RequireConsent = false,


                RedirectUris = new List<string>

                {

                    REMOVED
                },


                PostLogoutRedirectUris = new List<string>
                {
                    REMOVED
                },


                AllowedCorsOrigins = new List<string>
                {
                    REMOVED
                },

                AccessTokenLifetime = 60,
                IdentityTokenLifetime = 60,
                AbsoluteRefreshTokenLifetime = 60 * 60 * 24,
                SlidingRefreshTokenLifetime = 60 * 15,
            },

@brockallen - 简而言之。我有一个应用程序是 MVC 和 WEBAPI 和 Anjulgarjs。我不认为这样的混合是明智的,但我继承了这个应用程序,现在我必须找到一种方法让它与 Idnetity Server 3 一起工作。

如有任何指导,我将不胜感激。请。

【问题讨论】:

    标签: asp.net-mvc identityserver3 thinktecture-ident-server


    【解决方案1】:

    我遇到了和你一样的问题。问题是您正在为 MVC 设置 cookie,但您没有设置过期日期,因此 MVC 不知道 cookie 已过期。您需要做的是通过以下方式设置 AuthenticationTicket 的到期日期:

                        n.AuthenticationTicket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn));
                        n.AuthenticationTicket.Properties.IssuedUtc = DateTime.Now;
                        //Add encrypted MVC auth cookie
                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
    

    我也设置了发布日期,但这不是强制性的

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 2019-09-28
      • 1970-01-01
      • 2014-07-18
      • 2015-10-01
      • 1970-01-01
      • 2017-09-05
      • 2012-06-05
      • 2018-10-17
      相关资源
      最近更新 更多