c# - 获取 OAuth session 的过期时间

标签 c# oauth owin asp.net-web-api2

要授予或撤销对我的 webapi 的访问权限,我使用 OAuth 密码和 token 刷新工作流。

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

  1. 使用用户名/密码/客户 ID 进行身份验证
  2. 检索访问 token 、刷新 token 和过期日期
  3. 在 token 时间过期后在客户端启动超时以刷新您的 token
  4. 继续第 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/

相关文章:

c# - C#中抽象类的构造函数

c# - 我应该使用 OAuth 跨服务器传递数据(从 JavaScript 到 C#)吗?

c# - 基本身份验证没有挑战

asp.net-web-api - 为 Web Api 2 和 OWIN token 身份验证启用 CORS

c# - 从 Web API OAuth Bearer 身份验证中检索用户信息

c# - 将应用程序安全组添加到 Azure VM

c# - 相同条件下的 Guard Clause 和 Exception 处理

ruby - 为什么 Mechanize 在看到错误的 OAuth 凭据时会引发 "undefined method ' 任何 ?'"?

c# - 从带参数的方法调用带参数的方法

ios - 适用于 iOS 的 Foursquare OAuthV2