OAuth 2.0如何验证令牌到期日期

时间:2017-06-28 11:48:46

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

我在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");

            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:-1)

使用

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

您可以在&#34; timespan.from(this)&#34;

中更改分钟,小时等