首页 > 解决方案 > .net Core 3 Web API JWT 未经授权

问题描述

我是身份验证领域的初学者,我正在尝试实现一个简单的示例来保护我的 api。

在我的登录操作中,我生成了一个 JWT,例如:

var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThIsIsAKeyT03ncrypt!4lw4ysUs3AStr0ng1"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
                issuer: "https://localhost:44392/",
                audience: "https://localhost:44392/",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),  
               signingCredentials: creds);

我的控制器标记如下:

[ApiController]    
[Route("api/[controller]")]
[Authorize]
public class WeatherForecastController : ControllerBase
{

StartUp 类处理身份验证,如:

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseAuthentication();

和:

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters()
                        {
                            ValidIssuer = "https://localhost:44392/",
                            ValidAudience = "https://localhost:44392/",
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThIsIsAKeyT03ncrypt!4lw4ysUs3AStr0ng1")),
                            ValidateLifetime = true
                        };
                    });

问题是,虽然我使用相同的对称密钥、颁发者和受众,但通过邮递员测试时,结果始终是状态 401。

在此处输入图像描述

是否有我缺少的设置/选项?欢迎任何帮助

标签: asp.net-corejwtasp.net-authorizationjwt-auth

解决方案


通过添加解决的问题

 services.AddAuthentication(cfg =>
    {
        cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })

在 StartUp 类中。


推荐阅读