首页 > 其他 > 详细

JWT的一个demo

时间:2020-09-28 15:01:41      阅读:30      评论:0      收藏:0      [点我收藏+]

首先Nuget中引入库:

Microsoft.AspNetCore.Authentication.JwtBearer

1、注入

Startup里ConfigureServices方法里

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    
                .AddJwtBearer(options =>    
                {    
                    options.TokenValidationParameters = new TokenValidationParameters    
                    {    
                        ValidateIssuer = true,    
                        ValidateAudience = true,    
                        ValidateLifetime = true,    
                        ValidateIssuerSigningKey = true,    
                        ValidIssuer = Configuration["Jwt:Issuer"],    
                        ValidAudience = Configuration["Jwt:Issuer"],    
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))    
                    };    
                });    

Configure方法里:

app.UseAuthentication();    

2、

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

3、CreateToken的方法

private string CreateToken(string userId, string userName)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(ClaimTypes.Name, userName),
            };

            var a= _configuration["Jwt:Key"];
            a = _configuration["Jwt:Issuer"];
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_configuration["Jwt:Issuer"],
                _configuration["Jwt:Issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

4、控制器中登录方法

 [HttpPost]
        public IActionResult Login(UserModel model)
        {
            IActionResult response = Unauthorized();
            var userInfo = CheckUser(model);
            if (userInfo != null)
            {
                var tokenString = CreateToken(userInfo.UserId, userInfo.UserName);
                response = Ok(new {token = tokenString});
            }

            return response;
        }

        private User CheckUser(UserModel model)
        {
            return new User() {UserId = "123456789", UserName = "test"};
        }
 public class UserModel
    {
        public string UserName { get; set; }

        public string Password { get; set; }
    }

5、Postman调试接口查看效果

JWT的一个demo

原文:https://www.cnblogs.com/dayang12525/p/13744355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!