asp.net-core - 如果与 JWT 承载身份验证一起使用,Asp.Net 核心 Web API 防伪验证将失败

标签 asp.net-core .net-core jwt asp.net-core-webapi x-xsrf-token

我正在尝试在 Asp.net core 3.0 web API 中使用防伪和 jwt 承载身份验证。我面临的奇怪问题是防伪工作非常好,但如果我尝试将 [Authorize] 过滤器与 [ValidateAntiForgeryToken] 一起添加到 Controller 操作, 然后 AntiForgery 验证失败并出现 Http 400 错误。

启动.cs:

services.AddCors();
services.AddControllers();
services.AddMvc();
services.AddAntiforgery
    (
    options =>
    {
        options.HeaderName = "X-XSRF-TOKEN";
        options.Cookie = new Microsoft.AspNetCore.Http.CookieBuilder()
        { Name = "X-XSRF-COOKIE" };
    }
    );
// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);

// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
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
    };
});

用户 Controller .cs:

[AllowAnonymous]
[IgnoreAntiforgeryToken]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]AuthenticateModel model)
{
    var user = _userService.Authenticate(model.Username, model.Password);
    var tokens = _antiforgery.GetAndStoreTokens(HttpContext);
    Response.Cookies.Append("X-XSRF-TOKEN", tokens.RequestToken, new Microsoft.AspNetCore.Http.CookieOptions
    {
        HttpOnly = false
    });
    if (user == null)
        return BadRequest(new { message = "Username or password is incorrect" });

    return Ok(user);
}

如果我在下面的操作中使用 [Authorize] 过滤器,Antiforgery 验证失败。如果我删除它,Antiforgery 验证似乎工作正常.

用户 Controller .cs:

[HttpGet]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult GetAll()
{
    var users = _userService.GetAll();
    return Ok(users);
}

这就是我生成 JWT token 的方式:

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Expires = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), 
    SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
user.Token = tokenHandler.WriteToken(token);

服务器日志:

info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "GetAll", controller = "Users"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult GetAll() on controller WebApi.Controllers.UsersController (WebApi).
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter[1]
      Antiforgery token validation failed. The provided antiforgery token was meant for a different claims-based user than the current user.
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The provided antiforgery token was meant for a different claims-based user than the current user.
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet)
   at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
      Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action WebApi.Controllers.UsersController.GetAll (WebApi) in 28.5729ms

尝试在调用 _antiforgery.GetAndStoreTokens(HttpContext) 之前设置 HttpContext.user 但没有成功。

最佳答案

在进入 Controller 之前,您需要在启动文件中设置防伪验证。请看下面的代码片段:

public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
{
    app.Use(next => context =>
    {
        string path = context.Request.Path.Value;

        if (
            string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
        {
            // The request token can be sent as a JavaScript-readable cookie, 
            // and Angular uses it by default.
            var tokens = antiforgery.GetAndStoreTokens(context);
            context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, 
                new CookieOptions() { HttpOnly = false });
        }

        return next(context);
    });
}

关于asp.net-core - 如果与 JWT 承载身份验证一起使用,Asp.Net 核心 Web API 防伪验证将失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476605/

相关文章:

c# - 单个数据库上具有多个 DbContext 的 EF Core 迁移

azure - Azure 中的 301 重定向

c# - 在 ASP.NET Core 中实现 "JSON Merge Patch"- 区分 null 和未定义属性的最佳方法

jwt - 我的 Azure AD B2C token 的 key 在哪里?

asp.net - 让 IMetadataDetailsProviders 在 ASP.NET Core 中多次运行

asp.net - 在 .Net Core 中使用 Swagger 在 API 方法中设置自定义路径前缀

javascript - 在 for 循环中使用 @ref 获取元素引用

c# - 如何在 docker 容器中运行 asp.net 核心应用程序?

go - 使用一个签名 key 对jwt进行签名安全吗?

c# - ASP.NET 中的 JWT token 验证