ASP.NET Core身份验证失败 [英] Asp.NET Core authentication failing
问题描述
我正在尝试向我的应用程序前端VueJS后端Asp.NET core 2.1添加身份验证,但最终却无法使它真正进行身份验证.
I'm trying to add authentication to my app, frontend VueJS backend Asp.NET core 2.1 but I'm failing to get it to actually authenticate in the end.
在Asp.NET中设置身份验证:
Setting up the authentication in 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被模拟为始终返回相同的硬编码用户.
My UserService is mocked to return the same hardcoded user always.
登录时,前端似乎正在发送从后端获取的正确令牌:
The frontend seems to be sending the correct token it gets from the backend when logging in:
但是,在调用授权的端点时,我仍然遭到拒绝:
But, I'm still getting rejected when calling authorized endpoints:
服务器报告以下日志:
<代码>Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [2]授权失败.信息:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [3]筛选器"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter"上的请求授权失败.信息:Microsoft.AspNetCore.Mvc.ChallengeResult [1]使用身份验证方案()执行ChallengeResult.信息:Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler [2]成功验证令牌.信息:Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler [12]AuthenticationScheme:承载受到了挑战.信息:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [2]在32.891毫秒内执行了动作DnaBackend.Controllers.DnaController.UploadFile(DnaBackend)信息:Microsoft.AspNetCore.Hosting.Internal.WebHost [2]请求完成41.847ms 401信息:Microsoft.AspNetCore.Server.Kestrel [32]连接ID"0HLIDVBUA1Q5P",请求ID"0HLIDVBUA1Q5P:00000003":应用程序已完成,没有读取整个请求正文.
有什么想法为什么会失败?如果这有任何区别,我也正在使用CORS.
Any ideas why this is failing? I'm using CORS too, if that makes any difference(?).
登录端点如下所示:
[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));
}
推荐答案
在我的情况下,我将 UseAuthorization
放在了 UseAuthentication
之前.
In my case it was that i had put UseAuthorization
before UseAuthentication
.
请确保这些方法的顺序如下:
Please make sure these methods are in the following order:
app.UseAuthentication();
app.UseAuthorization();
这篇关于ASP.NET Core身份验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!