【问题标题】:.net Core 3 Web API JWT unauthorized.net Core 3 Web API JWT 未经授权
【发布时间】:2020-02-11 09:49:06
【问题描述】:

我是身份验证领域的初学者,我正在尝试实现一个简单的示例来保护我的 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。

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

【问题讨论】:

  • 您是说您尝试了两种方法,一种有效,另一种无效,或者两种方法都无效?当您说“在登录操作中”时,您是指控制器操作方法吗?为什么要在那里生成 JWT?
  • @TomW 感谢您的评论。好吧,我的解决方案中有一种方法。当用户要登录并且身份服务器找到他的凭据后,我会生成一个 JWT。这个 JWT 需要在 Startup 类中处理。我的问题的解决方案在下面得到了回答(我错过了一些设置)。虽然,为什么我不应该在登录操作中生成?有没有更好的方法呢?谢谢。

标签: asp.net-core jwt asp.net-authorization jwt-auth


【解决方案1】:

通过添加解决的问题

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

在 StartUp 类中。

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 2020-03-28
    • 2020-03-04
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-07-13
    • 2017-01-12
    相关资源
    最近更新 更多