gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:39:20 28 4
gpt4 key购买 nike

我正在尝试在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com