获取OAuth会话的到期时间

问题描述 投票:1回答:2

要授予或撤消对我的webapis的访问权限,我使用OAuth密码和tokenrefreshworkflow。

如果我理解正确的一切,工作流应该是这样的:

  1. 使用用户名/密码/客户端ID进行身份验证
  2. 检索accesstoken,refreshtoken和失效日期
  3. 客户端启动超时以在过期令牌时间后刷新令牌
  4. 继续使用子弹2 - >依此类推......

到目前为止,上述进展正常。我的问题是,在身份验证请求之后,我没有从用户原则中获得过期时间。因此,如果我使用stateles webclients,我需要更新我的令牌以检索新的过期日期,即使用户令牌有效:

我想要的是像/ api / session / information服务,它提供有关经过身份验证的用户的当前会话的一般信息。

如何检索我的过期日期=)

[HttpGet]
[ActionName("information")]
public HttpResponseMessage Information(BaseRequest request)
{

    var p = Request.GetRequestContext().Principal;

    /* here i need help =) */
}
c# oauth owin asp.net-web-api2
2个回答
5
投票

您的访问令牌(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>);

那是你在找什么?否则请告诉我。乐于帮助 :-)


1
投票

只是为了扩展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
© www.soinside.com 2019 - 2024. All rights reserved.