3

我正在尝试在 Asp.net core 3.0 Web API 中使用 Anti-forgery 和 jwt 不记名身份验证。我面临的奇怪问题是防伪工作非常好,但是如果我尝试将[Authorize]过滤器与控制器操作一起添加[ValidateAntiForgeryToken],则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
    };
});

用户控制器.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验证似乎工作正常。

用户控制器.cs:

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

这就是我生成 JWT 令牌的方式:

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

HttpContext.user在打电话之前尝试设置,_antiforgery.GetAndStoreTokens(HttpContext)但没有奏效。

4

1 回答 1

2

在进入控制器之前,您需要在启动文件中设置 antiforgeryvalidation。请参见下面的代码片段:

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);
    });
}

于 2019-12-25T16:59:53.570 回答