首页 > 其他分享 > .net6 使用 JWT

.net6 使用 JWT

时间:2022-09-26 21:00:39浏览次数:63  
标签:return app 使用 JWT new var net6 configuration

  1. 安装 Nuget 包 Microsoft.AspNetCore.Authentication.JwtBearer

  2. Program.cs 里添加JWT

    //添加jwt验证:
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options=>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["JWT:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["JWT:Audience"],
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
        };
    });
    
  3. 下面的app添加这个

    app.UseAuthentication();

    app.UseAuthorization();

    app.UseHttpsRedirection();
    
    app.UseCors();
    
    app.UseAuthentication();//在前 鉴权
    app.UseAuthorization();//在后  授权
    
    app.MapControllers();
    
    app.Run();
    
  4. TokenHelper类 模型也放在这里 比如我放了一个实体进去拿token的时候也会拿出一个实体

    public class TokenHelper
    {
    	private readonly IConfiguration _configuration;
    	private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler;
    	public TokenHelper(IConfiguration configuration, JwtSecurityTokenHandler jwtSecurityTokenHandler)
    	{
    	    _configuration = configuration;
    	    _jwtSecurityTokenHandler = jwtSecurityTokenHandler;
    	}
    	/// <summary>
    	/// 创建加密JwtToken
    	/// </summary>
    	/// <param name="user"></param>
    	/// <returns></returns>
    	public string CreateJwtToken<T>(T user)
    	{
    	  var claimList = this.CreateClaimList(user);
    	  //  从 appsettings.json 中读取SecretKey
    	  var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
          // 从 appsettings.json 中读取Expires
          var expires = Convert.ToDouble(_configuration["JWT:Expires"]);
          //  选择加密算法
          var algorithm = SecurityAlgorithms.HmacSha256;
          // 生成Credentials
          var signingCredentials = new SigningCredentials(secretKey, algorithm);
          JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
             _configuration["JWT:Issuer"],     //Issuer
              _configuration["JWT:Audience"],   //Audience
              claims: claimList,
              DateTime.Now,                    //notBefore
              DateTime.Now.AddDays(expires),   //expires
              signingCredentials               //Credentials
              );
           string jwtToken = _jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
           return jwtToken;
         }
    
         public T GetToken<T>(string Token)
         {
           Type t = typeof(T
           object objA = Activator.CreateInstance(t);
           var b = _jwtSecurityTokenHandler.ReadJwtToken(Token);
           foreach (var item in b.Claims)
           {
              PropertyInfo _Property = t.GetProperty(item.Type);
              if (_Property != null && _Property.CanRead)
              {
                  _Property.SetValue(objA, item.Value, null);
              }
           }
           return (T)objA;
         }
    
         /// <summary>
         /// 创建包含用户信息的CalimList
         /// </summary>
         /// <param name="authUser"></param>
         /// <returns></returns>
         private List<Claim> CreateClaimList<T>(T authUser)
         {
            var Class = typeof(T);
            List<Claim> claimList = new List<Claim>();
            foreach (var item in Class.GetProperties())
            {
                claimList.Add(new Claim(item.Name, Convert.ToString(item.GetValue(authUser))));
            }
            return claimList;
         }
    }
    
  5. appsettings.json

     "JWT": {
        "Issuer": "随意默认是自己的域名",//发行人
        "Audience": "前端随写",//拥有者
        "SecretKey": "666666666666666666",//16位以上
        "Expires": 7//过期时间 单位:天
      }
    
  6. 控制器中颁发token

    [Authorize]//授权
    //控制器
    private readonly TokenHelper _tokenHelper;
    private readonly IUserService _userServices;
    public UserController(IUserService userServices,TokenHelper tokenHelper)
    {
        _userServices = userServices;
        _tokenHelper = tokenHelper;
    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpPost]
    public IActionResult Login(LoginDto user)
    {
        if (user==null)
        {
            return BadRequest();
        }
        var result = _userServices.Login(user);
        if (result==null)
        {
            return Ok(new ResponseModel { Code = 0, Message = "登录失败" });
        }
        //颁发token
        var token = _tokenHelper.CreateJwtToken(result);
        Response.Headers["Header_Token"] = token;
        Response.Headers["Access-Control-Expose-Headers"] = "token";
        return Ok(new ResponseModel { Code=1, Data=result, Message="登录成功" });
    }
    

标签:return,app,使用,JWT,new,var,net6,configuration
From: https://www.cnblogs.com/Coriander-Leo/p/16732458.html

相关文章