ASP.Net Core 3 API始终返回401- JwtBearer

问题描述 投票:0回答:1

我有一个ASP .NET Core Web API,并且出于授权目的生成JWT令牌,但是每当我拍摄请求时,我都会得到401-未经授权

操作顺序:

     1. GET for token
     2. GET for user <-- 401

我检查了jwt.io上的令牌,它是正确的。当我删除[[授权]时,一切正常[]]]

Startup.cs

   public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            var appSettingsSection = Configuration.GetSection("Jwt");
            services.Configure<JwtSettings>(appSettingsSection);
            var appSettings = appSettingsSection.Get<JwtSettings>();
            services.AddControllers();
            services.AddOptions();

            services.AddAuthentication(x => 
            {
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(x=>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidAudience = appSettings.Issuer,
                    ValidIssuer = appSettings.Issuer,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Key))
                };

            }
            );
        }



  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

            });
        }

CreateToken方法

 public JwtDto CreateToken(string email, string role)
        {
            var now = DateTime.UtcNow;
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,email),
                new Claim(ClaimTypes.Role, role),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat,now.ToTimestamp().ToString(),ClaimValueTypes.Integer64)
            };


            var expires = now.AddMinutes(360);
            var singingCredentails = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Key)),SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: _settings.Issuer,
                claims: claims,
                notBefore: now,
                expires: expires,
                signingCredentials: singingCredentails
            );
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);

            return new JwtDto
            {
                Token = token,
                Expiry = expires.ToTimestamp()
            };
        }

GetToken-API

[HttpGet]
[Route("token")]
public IActionResult GetToken()
{
    var token = _jwtHandler.CreateToken("test", "user");
    return Json(token);
}

GetUser-API

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [HttpGet("{email}")]
    public async Task<UserDto> Get(string email)
    {
      return  await _userService.GetUserAsync(email);
    }

Token request

我有一个ASP .NET Core网络api,并且出于授权目的生成JWT令牌,但是每当我拍摄请求时,我都会得到401-未经授权。操作顺序:1.获取令牌2. ...

c# .net api jwt core
1个回答
0
投票

我遇到了完全相同的问题,并认为问题出在Startup.cs的Configure()方法中。您具有正确的顺序的正确UseAuthentication()和UseAuthorization()调用,这很重要,这也是我发现的问题。因此,对于您来说,我认为问题在于缺少UseCors()调用。我正在工作的Startup类如下:

© www.soinside.com 2019 - 2024. All rights reserved.