ASP.NET核心JWT承载令牌自定义验证

San*_*tak 9 c# asp.net jwt asp.net-core asp.net-core-middleware

经过大量阅读,我找到了一种实现自定义JWT承载令牌验证器的方法,如下所示.

Starup.cs 代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
         ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseStaticFiles();

    app.UseIdentity();

    ConfigureAuth(app);

    app.UseMvcWithDefaultRoute();            
}

private void ConfigureAuth(IApplicationBuilder app)
    {

        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));


        var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,
            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = Configuration.GetSection("TokenAuthentication:Audience").Value,
            // Validate the token expiry
            ValidateLifetime = true,
            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };

        var jwtBearerOptions = new JwtBearerOptions();
        jwtBearerOptions.AutomaticAuthenticate = true;
        jwtBearerOptions.AutomaticChallenge = true;
        jwtBearerOptions.TokenValidationParameters = tokenValidationParameters;
        jwtBearerOptions.SecurityTokenValidators.Clear();
        //below line adds the custom validator class
        jwtBearerOptions.SecurityTokenValidators.Add(new CustomJwtSecurityTokenHandler());
        app.UseJwtBearerAuthentication(jwtBearerOptions);

        var tokenProviderOptions = new TokenProviderOptions
        {
            Path = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
            Audience = Configuration.GetSection("TokenAuthentication:Audience").Value,
            Issuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
            SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
        };

        app.UseMiddleware<TokenProviderMiddleware>(Options.Create(tokenProviderOptions));
    }
Run Code Online (Sandbox Code Playgroud)

以下是自定义验证器类:

public class CustomJwtSecurityTokenHandler : ISecurityTokenValidator
{
    private int _maxTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;
    private JwtSecurityTokenHandler _tokenHandler;

    public CustomJwtSecurityTokenHandler()
    {
        _tokenHandler = new JwtSecurityTokenHandler();
    }

    public bool CanValidateToken
    {
        get
        {
            return true;
        }
    }

    public int MaximumTokenSizeInBytes
    {
        get
        {
            return _maxTokenSizeInBytes;
        }

        set
        {
            _maxTokenSizeInBytes = value;
        }
    }

    public bool CanReadToken(string securityToken)
    {
        return _tokenHandler.CanReadToken(securityToken);            
    }

    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        //How to access HttpContext/IP address from here?

        var principal = _tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken);

        return principal;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果被盗令牌,我想添加一层额外的安全性来验证请求是来自生成令牌的同一客户端.

问题:

  1. 有什么方法可以HttpContextCustomJwtSecurityTokenHandler类中访问,以便我可以添加基于当前客户端/请求者的自定义验证?
  2. 有没有其他方法可以使用这样的方法/中间件验证请求者的真实性?

Set*_*Set 5

在ASP.NET Core中HttpContext可以使用IHttpContextAccessor服务获得。使用DI将IHttpContextAccessor实例传递到处理程序中并获取IHttpContextAccessor.HttpContext属性值。

IHttpContextAccessor默认情况下,该服务未注册,因此您首先需要在Startup.ConfigureServices方法中添加以下内容:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)

然后修改您的CustomJwtSecurityTokenHandler课程:

private readonly IHttpContextAccessor _httpContextAccessor;

public CustomJwtSecurityTokenHandler(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
    _tokenHandler = new JwtSecurityTokenHandler();
}

... 

public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
    var httpContext = _httpContextAccessor.HttpContext;
}
Run Code Online (Sandbox Code Playgroud)

您还应该使用DI技术进行JwtSecurityTokenHandler实例化。考虑依赖注入的文件,如果你是新来这一切的东西。


更新:如何手动解决依赖关系(更多信息,在这里

修改Configure使用方法IServiceProvider serviceProvider

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
         ILoggerFactory loggerFactory, IApplicationLifetime appLifetime,
         IServiceProvider serviceProvider)
{
    ...
    var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
    // and extend ConfigureAuth
    ConfigureAuth(app, httpContextAccessor);
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • @SangSuantak。也许现在我理解您错了,但是:`当实例化CustomJwtSecurityTokenHandler时,httpContextAccessor.Context将为null。-是的,此刻上下文不存在,这就是为什么在初始化期间只需要存储HttpContextAccessor实例的原因,应该调用` ValidateToken`方法中的httpContextAccessor.HttpContext`,因为稍后将在HTTP请求到来时调用它,因此将创建HttpContext。 (3认同)
  • @设置您的示例不完整。`jwtBearerOptions.SecurityTokenValidators.Add(new CustomJwtSecurityTokenHandler());`要求您在添加验证器时手动注入http上下文访问器 (2认同)