在Asp .net core中使用Jwt登录验证

  1. 安装Jwt Nuget包image-20210826145132493

  2. 在startup中添加验证授权中间件(在路由之后)image-20210826145715110

  3. 在appsettings中添加Jwt所需配置image-20210826145849039

  4. 在登录控制器中创建Jwt

                var signingAlgorithm = SecurityAlgorithms.HmacSha256;
                var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                };
    
                var roleNames = await _userManager.GetRolesAsync(user);
                foreach (var roleName in roleNames)
                {
                    var roleClaim = new Claim(ClaimTypes.Role, roleName);
                    claims.Add(roleClaim);
                }
    
                var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
                var signingkey = new SymmetricSecurityKey(secretByte);
                var signingCredentials = new SigningCredentials(signingkey,         	signingAlgorithm);
    
                var token = new JwtSecurityToken(
                    issuer: _configuration["Authentication:Issuer"],
                    audience: _configuration["Authentication:Audience"],
                    claims,
                    notBefore: DateTime.UtcNow,
                    expires: DateTime.UtcNow.AddDays(1),
                    signingCredentials
                );
    
                var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
    
  5. ConfigureServices中配置jwtimage-20211025123700886

  6. 在需要验证是否登录的Action加上Attribute

    [Authorize(AuthenticationSchemes = "Bearer")]
    
posted @ 2021-08-26 16:02  bleso  阅读(54)  评论(0编辑  收藏  举报