需要检查jwt令牌在asp.net核心中是否有效/已过期 [英] Need to check of jwt token is valid/expired in asp.net core

查看:218
本文介绍了需要检查jwt令牌在asp.net核心中是否有效/已过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了生成JWT令牌,我使用以下代码:

In order to generate JWT token I am using the following code:

  var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(_consumerConfiguration.SecretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, "ConsumerId")
                }),
                Expires = DateTime.Now.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);

这是我在RegisterServices中的代码

This is my code in RegisterServices

  var appSettingsSection = configuration.GetSection("ConsumerConfiguration");
            services.Configure<ConsumerConfiguration>(appSettingsSection);

            var appSettings = appSettingsSection.Get<ConsumerConfiguration>();

            var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            services.AddScoped<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, ConsumerAuthorizationHandler>();

我将其用作过滤器,以在应用程序中全局注册自定义授权处理程序:

I using this as a filter to register the custom authorization handler globally in the application:

 var policy = new AuthorizationPolicyBuilder().RequireCustomClaim(ClaimTypes.Name).
                AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).Build();

options.Filters.Add(new AuthorizeFilter(policy));
            })

这是我的自定义授权处理程序

and this is my custom authorization handler

    #region constructor
    public ConsumerAuthorizationHandler(IOptions<ConsumerConfiguration> consumerConfiguration)
    {
        _consumerConfiguration = consumerConfiguration.Value;
    }
    #endregion
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequireClaim requirement)
    {
        if (!_consumerConfiguration.EnableAuthorizationFilter)
            context.Succeed(requirement);

        var hasClaim = context.User.Claims.Any(x => x.Type == requirement.ClaimType);

        if (hasClaim)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

public static class AuthorizationPolicyBuilderExtensions
{
    public static AuthorizationPolicyBuilder RequireCustomClaim(this AuthorizationPolicyBuilder builder, string claimType)
    {
       return builder.AddRequirements(new CustomRequireClaim(claimType));
    }
}

问题是:如何检查JWT是否过期?该令牌似乎没有过期.我必须添加什么代码来检查令牌是否已过期?

The problem is: How can I check if the JWT is expired? The token seems not to expire. What code do I have to add that it will check if the token is expired?

推荐答案

默认情况下,身份验证流程会为您处理此问题.它甚至在您到达授权层之前就发生了.

The authentication flow handles this for you by default. It happens even before you hit your authorization layers.

这篇关于需要检查jwt令牌在asp.net核心中是否有效/已过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆