JWT令牌验证

时间:2019-01-30 13:34:21

标签: c# asp.net asp.net-mvc jwt asp.net-core-webapi

我试图对除LogIn和Register动作以外的每个动作执行JWT验证,但是我找不到在动作过滤器中执行JWT验证的方法,因为我需要令牌,并且令牌位于this.Request.Headers上。 这是有效的验证方法:

try
{
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    string sToken = token.Substring(7, token.Length - 7);

    if (!tokenHandler.CanReadToken(sToken))
    {
        return false;
    }

    JwtSecurityToken jwtToken = tokenHandler.ReadToken(sToken) as JwtSecurityToken;

    if (jwtToken == null)
    {
        return false;
    }

    TokenValidationParameters parameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        RequireExpirationTime = true,
        ValidAudience = "http://localhost",
        ValidIssuer = "http://localhost",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(StandardValues.SecretKey))
    };

    SecurityToken securityToken;
    ClaimsPrincipal principal = tokenHandler.ValidateToken(sToken, parameters, out securityToken);

    if (principal == null)
    {
        return false;
    }
}
catch (Exception ex)
{
    return false;
}

return true;

我有多个控制器要在其上执行验证。 在发送令牌作为验证方法的参数时,请让我知道如何在操作之前和之后(进入操作过滤器或其他方式)执行此验证。

1 个答案:

答案 0 :(得分:0)

在我们的ASP.Net WebApi中,我们使用以下代码来验证令牌:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = $"https://{Configuration.GetValue<string>("AppServiceNameOutput")}",
            ValidAudience = $"https://{Configuration.GetValue<string>("AppServiceNameOutput")}",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(Configuration.GetValue<string>("SigningKey"))),
        };
        options.Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                var tokenBlackList = context.HttpContext.RequestServices.GetRequiredService<ITokenBlackList>();
                var tokenParser = context.HttpContext.RequestServices.GetRequiredService<ITokenParser>();
                var bearer = context.HttpContext.Request.Headers["Authorization"];

                if (String.IsNullOrEmpty(bearer))
                {
                    bearer = context.Request.Query["access_token"];
                }

                var token = tokenParser.GetBearerTokenFromAuthHeaderString(bearer);
                if (tokenBlackList.TokenIsBlackListed(token).Result)
                {
                    context.Fail("Token has expired");
                }
                return Task.CompletedTask;
            }
        };
    });

然后,在每个控制器操作上,我们指定是否应该授权端点以及允许访问哪些策略。

[Authorize(Policy = "ManagerOnly")]
[HttpPost]
public IActionResult Update([FromBody] UpdateAppRequest request)