zoukankan      html  css  js  c++  java
  • JWT的一个demo

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

  • 相关阅读:
    hive 数据hadoop数据etl交换
    团队冲刺(三)
    团队冲刺(二)
    CVPR2019论文热词云的实现
    团队冲刺(一)
    团队开发之电梯演讲----团队项目介绍--“益青春APP”
    android的finish()方法
    java web项目通过外网ip访问
    MySQL出现错误1205-Lock wait timeout exceeded; try restarting transaction
    团队开发(自己的理解)
  • 原文地址:https://www.cnblogs.com/dayang12525/p/13744355.html
Copyright © 2011-2022 走看看