IdentityServer MVC 令牌过期

7
我刚接触身份认证服务器,还有一个关键概念我不太明白。我正在使用MVC教程中的代码。
如果我在我的Home控制器上添加[Authorize]属性,并访问我的网站,我会被重定向到IdentityServer。然后,我使用我的用户名和密码进行登录。然后,我使用一些自定义代码进行身份验证。我得到了一个AccessToken,然后就可以访问Home控制器了。
我的客户端设置如下:
  new Client {
                ClientId = "mvc",
                ClientName = "MVC Client",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                ClientSecrets = new List<Secret>{new Secret("secret".Sha256())},
                RequireConsent = false,
                AccessTokenLifetime = 1,

                // where to redirect to after login
                RedirectUris = new List<string>{"http://localhost:5002/signin-oidc"},

                // where to redirect to after logout
                PostLogoutRedirectUris = new List<string>{"http://localhost:5002"},

                AllowedScopes = new List<string>
                {
                    StandardScopes.OpenId.Name,
                    StandardScopes.Profile.Name,
                    StandardScopes.OfflineAccess.Name,
                }
            }

我的访问令牌是

{
  "nbf": 1474697839,
  "exp": 1474697840,
  "iss": "http://localhost:5000",
  "aud": "http://localhost:5000/resources",
  "client_id": "mvc",
  "scope": [
    "openid",
    "profile"
  ],
  "sub": "26296",
  "auth_time": 1474697838,
  "idp": "local",
  "amr": [
    "pwd"
  ]
}

当我将我的AccessTokenLifetime设置为1时,当发送令牌以调用API等时,令牌将无效。但是,我仍然可以访问网站。
最好的方法是什么以使MVC网站确认我的令牌是否已过期?这可能是刷新令牌发挥作用的地方。
注意:设置AccessTokenLifetime为1仅供测试,以便我可以快速测试事物。
2个回答

3
您需要将用户身份验证寿命设置为与访问令牌相匹配。如果使用OpenIdConnect,可以使用以下代码完成此操作:

您需要将用户身份验证寿命设置为与访问令牌相匹配。如果使用OpenIdConnect,可以使用以下代码完成此操作:

.AddOpenIdConnect(option =>
{
...

option.Events.OnTicketReceived = async context =>
{
    // Set the expiry time to match the token
    if (context?.Properties?.Items != null && context.Properties.Items.TryGetValue(".Token.expires_at", out var expiryDateTimeString))
    {
        if(DateTime.TryParse(expiryDateTimeString, out var expiryDateTime))
        {
            context.Properties.ExpiresUtc = expiryDateTime.ToUniversalTime();
        }
    }
};
});

假设你正在使用cookie身份验证?如果是这样,您可能需要关闭滑动过期。 滑动过期将在处理超过过期时间窗口一半的请求时自动刷新cookie。 然而,访问令牌不会作为此过程的一部分被刷新。 因此,您应该让用户认证生命周期运行到结束,此时它将过期,并且将使用刷新令牌自动检索新的访问令牌。
.AddCookie(options =>
            {
                // Do not re-issue a new cookie with a new expiration time.
                // We need to let it expire to ensure we get a fresh JWT within the token lifetime.
                options.SlidingExpiration = false;
            })

-1

可能是这样的吗?

var user = HttpContext.Current.User.Identity;
                    if (!user.IsAuthenticated)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接