一、Net 6环境下的.net core项目里如何使用JWT。

  第一步,在Nuget引入JWT、Microsoft.AspNetCore.Authentication.JwtBearer这两个NuGet包

.NET6 JWT(生成Token令牌)-LMLPHP

  第二步,在appsettings.json配置相关配置

  .NET6 JWT(生成Token令牌)-LMLPHP

  第三步,在Program.cs中注册

.NET6 JWT(生成Token令牌)-LMLPHP

  第四步,定义注册存入TokenHelper类,方便对JWT令牌进行管理,实现接口:

.NET6 JWT(生成Token令牌)-LMLPHP

   第五步,在构造函数 还有IOC 容器中注入:

.NET6 JWT(生成Token令牌)-LMLPHP

.NET6 JWT(生成Token令牌)-LMLPHP

   第六步,登录方法中可直接调用获取 Token 值

.NET6 JWT(生成Token令牌)-LMLPHP

 纯代码: ->->->->

appsettings.json

----------------------------------------------------------------

"Authentication": {
"SecretKey": "nadjhfgkadshgoihfkajhkjdhsfaidkuahfhdksjaghidshyaukfhdjks",
"Issuer": "www.adsfsadfasdf",
"Audience": "www.adsfsadfasdf"
}

----------------------------------------------------------------

Program.cs

----------------------------------------------------------------

//JWT认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
//取出私钥
var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
  //验证发布者
  ValidateIssuer = true,
  ValidIssuer = builder.Configuration["Authentication:Issuer"],
  //验证接收者
  ValidateAudience = true,
  ValidAudience = builder.Configuration["Authentication:Audience"],
  //验证是否过期
  ValidateLifetime = true,
  //验证私钥
  IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});

----------------------------------------------------------------

TokenHelper.cs

----------------------------------------------------------------

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 signingAlogorithm = SecurityAlgorithms.HmacSha256;
  var claimList = this.CreateClaimList(user);
  //Signature
  //取出私钥并以utf8编码字节输出
  var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
  //使用非对称算法对私钥进行加密
  var signingKey = new SymmetricSecurityKey(secretByte);
  //使用HmacSha256来验证加密后的私钥生成数字签名
  var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
  //生成Token
  var Token = new JwtSecurityToken(
  issuer: _configuration["Authentication:Issuer"], //发布者
  audience: _configuration["Authentication:Au=dience"], //接收者
  claims: claimList, //存放的用户信息
  notBefore: DateTime.UtcNow, //发布时间
  expires: DateTime.UtcNow.AddDays(1), //有效期设置为1天
  signingCredentials //数字签名
  );
//生成字符串token
  var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
  return TokenStr;
}

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(UserDto);
  List<Claim> claimList = new List<Claim>();
  foreach (var item in Class.GetProperties())
  {
    if(item.Name=="UPass")
  {
    continue;
  }
    claimList.Add(new Claim(item.Name, Convert.ToString(item.GetValue(authUser))));
 }
  return claimList;
}
}

----------------------------------------------------------------

控制器API中

----------------------------------------------------------------

TokenHelper _tokenHelper;

public UserController(TokenHelper tokenHelper, JwtSecurityTokenHandler jwtSecurityTokenHandler)
{
  _tokenHelper = tokenHelper;
  _jwtSecurityTokenHandler = jwtSecurityTokenHandler;
}

//JWT
[AllowAnonymous]
[HttpPost]
public IActionResult JWTlogin(LoginDto user) //
{
  //1.验证用户账号密码是否正确
  if (user == null)
  {
    return BadRequest();
  }
  var result = _userServices.Login(user);
  if (result == null)
  {
    return Ok(new ResponseModel { Code = 0, Message = "登录失败" });
  }
  else
  {
    var Token=Response.Headers["TokenStr"] = _tokenHelper.CreateJwtToken(result);
    Response.Headers["Access-Control-Expose-Headers"] = "TokenStr";
    return Ok(Token);
  }
}

----------------------------------------------------------------

IOC容器中

----------------------------------------------------------------

//用于Jwt的各种操作
builder.RegisterType<JwtSecurityTokenHandler>().InstancePerLifetimeScope();
//自己写的支持泛型存入Jwt 便于扩展
builder.RegisterType<TokenHelper>().InstancePerLifetimeScope();

----------------------------------------------------------------

09-26 21:00