我是身份服务器的新手,我的理解中缺少一个关键概念。
我正在使用来自 MVC tutorial 的代码.
如果我用属性 [Authorize]
装饰我的 Home Controller 并访问我的网站,我重定向到 IdentityServer
.然后我使用我的用户名和密码登录。然后我使用一些自定义代码并进行身份验证。我得到一个 AccessToken,然后我可以访问 Home Controller 。
我的客户端设置如下:
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,
}
}
我的访问 token 是
{
"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 我的 token 在发送以调用 API 等时将无效。但是,我仍然可以访问该网站。让 MVC 网站确认我的 token 未过期的最佳方法是什么?这可能是刷新 token 发挥作用的地方。
备注
AccessTokenLifetime
设置为 1 仅用于测试,以便我可以快速测试。
最佳答案
您需要设置用户身份验证生命周期以匹配访问 token 的生命周期。如果使用 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。但是,访问 token 不会作为其中的一部分刷新。因此,您应该让用户身份验证生命周期运行到最后,届时它将过期,并且将使用刷新 token 自动检索新的访问 token 。
.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;
})
关于asp.net-mvc - IdentityServer MVC token 到期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39673231/