要授予或撤消对我的webapis的访问权限,我使用OAuth密码和tokenrefreshworkflow。
如果我理解正确的一切,工作流应该是这样的:
到目前为止,上述进展正常。我的问题是,在身份验证请求之后,我没有从用户原则中获得过期时间。因此,如果我使用stateles webclients,我需要更新我的令牌以检索新的过期日期,即使用户令牌有效:
我想要的是像/ api / session / information服务,它提供有关经过身份验证的用户的当前会话的一般信息。
如何检索我的过期日期=)
[HttpGet]
[ActionName("information")]
public HttpResponseMessage Information(BaseRequest request)
{
var p = Request.GetRequestContext().Principal;
/* here i need help =) */
}
您的访问令牌(JWT?)应包含到期声明。在JWT中,它是“exp”,显示自1970-1-1以来的秒数。在javascript中你可以这样得到一个日期:
new Date(<exp> * 1000);
在.Net / C#中你可以这样做:
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(<exp>);
那是你在找什么?否则请告诉我。乐于帮助 :-)
只是为了扩展Henrik N.的答案。如果您在C#中,那么您可以在JWTSecurityTokenHandler
(Nuget:System.IdentityModel.Tokens.Jwt
)中使用Install-Package System.IdentityModel.Tokens.Jwt
来读取令牌,并且生成的JwtSecurityToken
对象为您提供了一些方便的属性,其中一个是ValidTo
,它将exp
声明转换为DateTime
对象为您Eg :
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