ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JWT的一个demo

2020-09-28 14:03:33  阅读:289  来源: 互联网

标签:string 一个 demo Jwt JWT var new configuration Issuer


首先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调试接口查看效果

标签:string,一个,demo,Jwt,JWT,var,new,configuration,Issuer
来源: https://www.cnblogs.com/dayang12525/p/13744355.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有