要授予或撤销对我的 webapi 的访问权限,我使用 OAuth 密码和 token 刷新工作流。
如果我理解正确,工作流程应该是这样的:
- 使用用户名/密码/客户 ID 进行身份验证
- 检索访问 token 、刷新 token 和过期日期
- 在 token 时间过期后在客户端启动超时以刷新您的 token
- 继续第 2 项 -> 等等。
到目前为止,上述进展进展顺利。我的问题是,在身份验证请求之后,我没有从用户原则中得到过期时间。因此,如果我使用 stateles webclients,我需要在每次请求时更新我的 token 以检索新的到期日期,即使用户 token 有效也是如此:/
我想要的是类似/api/session/information 服务的东西,它提供有关经过身份验证的用户的当前 session 的一般信息。
我如何检索我的过期日期 =)
[HttpGet]
[ActionName("information")]
public HttpResponseMessage Information(BaseRequest request)
{
var p = Request.GetRequestContext().Principal;
/* here i need help =) */
}
最佳答案
只是稍微扩展一下 Henrik N. 的回答。如果您使用的是 C#,则可以在 System.IdentityModel.Tokens.Jwt
中使用 JWTSecurityTokenHandler
(Nuget:Install-Package System.IdentityModel.Tokens.Jwt
) 读取 token ,生成的 JwtSecurityToken
对象为您提供了一些方便的属性,其中之一是 ValidTo
,它转换 exp
声明为您生成一个 DateTime
对象,例如:
var tokenString = GetTokenString(); // Arbitrary method to get the token
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadToken(tokenString) as JwtSecurityToken;
var tokenExpiryDate = token.ValidTo;
// If there is no valid `exp` claim then `ValidTo` returns DateTime.MinValue
if(tokenExpiryDate == DateTime.MinValue) throw new Exception("Could not get exp claim from token");
// If the token is in the past then you can't use it
if(tokenExpiryDate < DateTime.UtcNow) throw new Exception($"Token expired on: {tokenExpiryDate}");
// Token is valid
关于c# - 获取 OAuth session 的过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829879/