【问题标题】:OAuth 2.0 How to validate token expiration dateOAuth 2.0 如何验证令牌到期日期
【发布时间】:2017-12-01 18:19:09
【问题描述】:

我在 MVC 项目中使用 MVC Web API。我使用 SimpleAuthorizationServerProvider 来生成令牌。我使用 AuthorizeForAPI 自定义属性来验证令牌。一切都很好。 我的问题是如何验证令牌过期日期,所以如果令牌已过期,我将从服务器发送一条消息告诉用户您的令牌已过期

这就是我生成令牌的方式

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }


        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);

    }


    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }

        return Task.FromResult<object>(null);
    }
}

这就是我验证令牌的方式

public class AuthorizeForAPI : AuthorizeAttribute
{

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        string AccessTokenFromRequest = "";
        if (actionContext.Request.Headers.Authorization != null)
        {
            // get the access token
            AccessTokenFromRequest = actionContext.Request.Headers.Authorization.Parameter;

            var user = HttpContext.Current.User.Identity;
            if (!user.IsAuthenticated)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized user");

            }
        }
    }
}

}

【问题讨论】:

  • 我强烈建议您使用身份 jwt 中间件来生成和验证您的访问令牌。它将负责所有必要的检查。此外:您在哪里生成令牌?您似乎只是设置了身份。

标签: asp.net-mvc asp.net-web-api oauth-2.0 access-token


【解决方案1】:

使用

 AccessTokenExpireTimeSpan = TimeSpan.FromDays(22), //22 day before expired

您可以在“timespan.from(this)”中将其更改为分钟、小时等

【讨论】:

  • 首先,我要感谢您的帮助和时间。我的问题不在于 Token Expire time 。我关于如何验证令牌过期时间的问题,换句话说,如何知道令牌是否已过期,因为如果令牌已过期,我将向客户端发送您的会话已过期的消息。谢谢
  • 你想要实时吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 2019-08-08
  • 2019-06-01
  • 1970-01-01
  • 2021-03-07
  • 2022-10-07
相关资源
最近更新 更多