代码之家  ›  专栏  ›  技术社区  ›  Ali Ha Quang

JWT-始终未经授权

  •  1
  • Ali Ha Quang  · 技术社区  · 3 年前

    我有一个非常简单的代码供用户登录,如下所示:

            [HttpPost]
            [Route("login")]
            public async Task<IActionResult> Login([FromBody] LoginModel model)
            {
                var user = await userManager.FindByEmailAsync(model.Email);
                if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
                {
                    var userRoles = await userManager.GetRolesAsync(user);
    
                    var authClaims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    };
    
                    foreach (var userRole in userRoles)
                    {
                        authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                    }
    
                    var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
    
                    var token = new JwtSecurityToken(
                        issuer: _configuration["JWT:ValidIssuer"],
                        audience: _configuration["JWT:ValidAudience"],
                        expires: DateTime.Now.AddHours(3),
                        claims: authClaims,
                        signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                        );
    
                    return Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
                }
                return Unauthorized();
            }
    

    这按预期向我发送了令牌

    Token Image

    当我使用令牌向简单控制器发送请求时,我得到401 Unauthorized

    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("getme")]
        public async Task<IActionResult> Get()
        {
            return Ok("Good");
        }
    }
    

    postman

    这是我的Startup.cs

        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
    
        // For Identity
        services.AddIdentity<ApplicationUser, IdentityRole>(o =>
        {
            // configure identity options
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 6;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
        // Adding Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
    
        // Adding Jwt Bearer
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidAudience = Configuration["JWT:ValidAudience"],
                ValidIssuer = Configuration["JWT:ValidIssuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
            };
        });
    

    以下是我的应用程序设置 appsettings

    我可以在以下网址验证令牌 https://jwt.io/ jwt.io

    出于某种原因,当我向发送请求时 TestController 它总是发回未经授权的响应。知道我做错了什么吗?

    0 回复  |  直到 3 年前
        1
  •  0
  •   Wai Ha Lee captain-yossarian from Ukraine    3 年前

    如果这对任何人都有帮助,那么问题出在我的 Startup 文件下 Configure 第一节 UseAuthentication 之后 UseAuthorization 这导致了问题。以下正确的顺序解决了问题

    app.UseAuthentication(); 
    app.UseRouting(); 
    app.UseAuthorization();
    app.UseHttpsRedirection();