Asp .net core JWT验证

Jwt

安装Nuget包          


3


 
 

 



 
 

1

IdentityModel 版本3.10.10
2
Microsoft.AspNetCore.Authorization 版本2.2.0
3
Microsoft.AspNetCore.Authentication.JwtBearer 版本2.2.0
    类          


17


 
 

 



 
 

1

public class JwtSettings
2
    {
3
        /// <summary>
4
        /// token是谁颁发的
5
        /// </summary>
6
        public string Issuer { get; set; }
7




8

        /// <summary>
9
        /// token可以给那些客户端使用
10
        /// </summary>
11
        public string Audience { get; set; }
12




13

        /// <summary>
14
        /// 加密的key(SecretKey必须大于16个,是大于,不是大于等于)
15
        /// </summary>
16
        public string SecretKey { get; set; }
17
    }
    appsetting配置添加          


6


 
 

 



 
 

1

,
2
  "JwtSettings": {
3
    "Issuer": "https://localhost:44336",//谁颁发的
4
    "Audience": "https://localhost:44336",//允许谁使用
5
    "SecretKey": "Hello-key----------"//加密密钥大于16
6
  }
    startup注入服务          


57


 
 

 



 
 

1

ConfigureServices()里面添加
2
            /*注入Jwt服务*/
3




4

            //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的
5
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
6
            var jwtsettings = new JwtSettings();
7
            //将配置绑定到JwtSettings实例中
8
            Configuration.Bind("JwtSettings", jwtsettings);
9
            //添加身份验证
10
            services.AddAuthentication(options=> {
11
                //认证middleware配置
12
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
13
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
14
            }).
15
            AddJwtBearer(o =>
16
            {
17
                //jwt token参数设置
18
                o.TokenValidationParameters = new TokenValidationParameters
19
                {
20
                    NameClaimType = JwtClaimTypes.Name,
21
                    RoleClaimType = JwtClaimTypes.Role,
22
                    //Token颁发机构
23
                    ValidIssuer = jwtsettings.Issuer,
24
                    //颁发给谁
25
                    ValidAudience = jwtsettings.Audience,
26
                    //这里的key要进行加密
27
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsettings.SecretKey)),
28




29

                    /***********************************TokenValidationParameters的参数默认值***********************************/
30
                    // RequireSignedTokens = true,
31
                    // SaveSigninToken = false,
32
                    // ValidateActor = false,
33
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
34
                    // ValidateAudience = true,
35
                    // ValidateIssuer = true, 
36
                    // ValidateIssuerSigningKey = false,
37
                    // 是否要求Token的Claims中必须包含Expires
38
                    // RequireExpirationTime = true,
39
                    // 允许的服务器时间偏移量
40
                    // ClockSkew = TimeSpan.FromSeconds(300),
41
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
42
                    // ValidateLifetime = true
43
                };
44
            });
45
            /*声明授权*/
46
            services.AddAuthorization(options =>
47
            {
48
                options.AddPolicy("IsUser", policy => policy.RequireClaim("IsAdmin", "false"));
49
                options.AddPolicy("IsAdmin", policy => policy.RequireClaim("IsAdmin", "true"));
50
                /*角色*/
51
                //options.AddPolicy("IsAdmin", policy => policy.RequireRole("Administrator", "admin","member"));
52
            });
53




54

configure()里面添加
55
            //身份授权认证
56
            app.UseAuthentication();
57
            app.UseHttpsRedirection();
    依赖注入,要验证的地方添加[Authorize],运行未验证的用户访问[AllowAnonymous]          


100


 
 

 



 
 

1

namespace Jwt.Controllers
2
{
3
    [ApiController]
4
    [Route("[controller]")]
5
    public class WeatherForecastController : ControllerBase
6
    {
7




8

        //获取JwtSettings对象信息
9
        private JwtSettings _jwtSettings;
10
        public WeatherForecastController(IOptions<JwtSettings> _jwtSettingsAccesser)
11
        {
12
            _jwtSettings = _jwtSettingsAccesser.Value;
13
        }
14




15

        /// <summary>
16
        /// 获取token
17
        /// </summary>
18
        /// <param name="user"></param>
19
        private object Token(user model)
20
        {
21
            //测试自己创建的对象
22
            var user = new user
23
            {
24
                id = 1,
25
                username = "138000000",
26
                password = "e10adc3949ba59abbe56e057f20f883e"
27
            };
28
            var tokenHandler = new JwtSecurityTokenHandler();
29




30

            var key = Encoding.UTF8.GetBytes(_jwtSettings.SecretKey);
31
            var authTime = DateTime.Now;//授权时间
32
            var expiresAt = authTime.AddDays(0.1);//过期时间
33
            var tokenDescripor = new SecurityTokenDescriptor
34
            {
35
                Subject = new ClaimsIdentity(new Claim[] {
36
                    new Claim(JwtClaimTypes.Audience,_jwtSettings.Audience),
37
                    new Claim(JwtClaimTypes.Issuer,_jwtSettings.Issuer),
38
                    new Claim(JwtClaimTypes.Name, user.username.ToString()),
39
                    new Claim("IsMember", member),  //声明授权
40
                }),
41
                Expires = expiresAt,
42
                //对称秘钥SymmetricSecurityKey
43
                //签名证书(秘钥,加密算法)SecurityAlgorithms
44
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
45
            };
46
            var token = tokenHandler.CreateToken(tokenDescripor);
47
            var tokenString = tokenHandler.WriteToken(token);
48
            var result = new
49
            {
50
                access_token = tokenString,
51
                token_type = "Bearer",
52
                profile = new
53
                {
54
                    id = user.id,
55
                    name = user.username,
56
                    phone = user.username,
57
                    auth_time = authTime,
58
                    expires_at = expiresAt
59
                }
60
            };
61
            return result;
62
        }
63




64





65

        [HttpGet]
66
        [Route("get_token")]
67
        public IActionResult Get()
68
        {
69
            return Ok(Token(null));
70
        }
71




72

        [Authorize(Policy = "IsUser")]
73
        [Authorize(Policy = "IsAdmin")]
74
        [Route("get_user_info")]
75
        [HttpGet]
76
        public IActionResult GetUserInfo()
77
        {
78
            //获取当前请求用户的信息,包含token信息
79
            var user = HttpContext.User;
80




81

            return Ok(
82
                new
83
                {
84
                    Issuer = base.User.Identity.Name,
85
                    message = "HAHA",
86
                    Issure2 = user.Identity,
87
                    user = user.Claims.Count(),
88
                    user1 = user.Claims.ElementAt(0).Value,
89
                    user2 = user.Claims.ElementAt(1).Value,
90
                    user3 = user.Claims.ElementAt(2).Value,
91
                    user4 = user.Claims.ElementAt(3).Value,
92
                    user5 = user.Claims.ElementAt(4).Value,
93
                    user6 = user.Claims.ElementAt(5).Value,
94
                    user7 = user.Claims.ElementAt(6).Value,
95
                    user8 = user.Claims.ElementAt(7).Value,
96
                }) ;
97
        }
98
    }
99
}
100







 
 




创建token
Asp .net core JWT验证

依赖注入
Asp .net core JWT验证
注入服务



Asp .net core JWT验证
注入服务1


Asp .net core JWT验证
获取信息


Asp .net core JWT验证
 

 
上一篇:Java笔记(day12)


下一篇:你知道JWT是什么吗?它和Session的区别又在哪里?