gpt4 book ai didi

Asp.NET Core 身份验证失败

转载 作者:行者123 更新时间:2023-12-01 07:50:41 24 4
gpt4 key购买 nike

我正在尝试向我的应用程序、前端 VueJS 后端 Asp.NET core 2.1 添加身份验证,但我最终未能对其进行实际身份验证。

在 Asp.NET 中设置身份验证:

        var key = Encoding.ASCII.GetBytes("mysecret");
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(userId);
if (user == null)
{
// return unauthorized if user no longer exists
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});

// configure DI for application services
services.AddScoped<IUserService, UserService>();

我的 UserService 被模拟为始终返回相同的硬编码用户。

登录时,前端似乎正在发送从后端获取的正确 token :

enter image description here

但是,在调用授权端点时我仍然被拒绝:

enter image description here

服务器报告以下日志:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[2]
Successfully validated the token.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action DnaBackend.Controllers.DnaController.UploadFile (DnaBackend) in 32.891ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 41.847ms 401
info: Microsoft.AspNetCore.Server.Kestrel[32]
Connection id "0HLIDVBUA1Q5P", Request id "0HLIDVBUA1Q5P:00000003": the application completed without reading the entire request body.

任何想法为什么会失败?
我也在使用 CORS,如果这有什么区别(?)。

登录端点如下所示:
    [HttpPost("login")]
public IActionResult Login([FromForm]LoginRequest loginRequest)
{

var user = _userService.Authenticate(loginRequest.Username, loginRequest.Password);

if (user == null)
return BadRequest(new { message = "Username or password is incorrect" });

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

// return basic user info (without password) and token to store client side
return Ok(new LoginResponse(user.Id, user.Username, user.FirstName, user.LastName, tokenString));
}

最佳答案

原来这只是在 startup.cs 中缺少一个 app.UseAuthentication() 的情况

当您还使用 AddAuthentication 配置服务时,ASP.NET 并不完全直观地要求这样做。

所以如果其他人有同样的问题,你现在知道为什么了:-)

关于Asp.NET Core 身份验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371337/

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