gpt4 book ai didi

ASP.NET 核心 JWT 身份验证总是抛出 401 未授权

转载 作者:行者123 更新时间:2023-12-03 15:05:18 25 4
gpt4 key购买 nike

我正在尝试尽可能简单地在我的 asp.net 核心 webAPI 上实现 JWT 身份验证。
我不知道我错过了什么,但它总是返回 401,即使使用 正确的不记名 token 。

这是我的 configureServices 代码

public void ConfigureServices(IServiceCollection services)
{
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(Encoding.ASCII.GetBytes("A_VERY_SECRET_SECURITY_KEY_FOR_JWT_AUTH")),
ValidateAudience = false,
ValidateIssuer = false,
};
}
);
services.AddControllers();

services.AddDbContext<dingdogdbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("dingdogdbContext")));
}


这就是我生成 token 的方式
        [AllowAnonymous]
[HttpPost("/Login")]
public ActionResult<User> Login(AuthModel auth)
{
var user = new User();
user.Email = auth.Email;
user.Password = auth.Password;
//var user = await _context.User.SingleOrDefaultAsync(u=> u.Email == auth.Email && u.Password==auth.Password);
//if(user==null) return NotFound("User not found with this creds");

//starting token generation...
var tokenHandler = new JwtSecurityTokenHandler();
var seckey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("A_VERY_SECRET_SECURITY_KEY_FOR_JWT_AUTH"));
var signingCreds = new SigningCredentials(seckey, SecurityAlgorithms.HmacSha256Signature);
var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
Subject = new System.Security.Claims.ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }),
SigningCredentials = signingCreds,
Expires = DateTime.UtcNow.AddDays(7),
});
user.Token = tokenHandler.WriteToken(token);
return user;
}

我在 app.useRouting() 之后添加了 app.useAuthorization()。
当我向/Login 发送 POST 请求时,我得到了 token 。但是当我使用 token 查询使用 postman 的任何其他端点时(在 postman 的授权/JWT 中添加 token )每次都获得 401 未经授权。
我还缺少什么吗?

最佳答案

请记住 UseAuthentication , UseRoutingUseAuthorization中间件必须正确,以便 ASP 框架正确地将身份上下文注入(inject) http 请求。
它应该如下所示:(.NET Core 3.1)
编辑:相同的代码适用于 .NET 5 & .NET 6

            app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

关于ASP.NET 核心 JWT 身份验证总是抛出 401 未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976960/

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