首页 > 其他分享 >.NET6 JWT(生成Token令牌)

.NET6 JWT(生成Token令牌)

时间:2022-09-26 21:01:24浏览次数:49  
标签:---------------------------------------------------------------- jwtSecurityToke

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

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

 

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

  

 

  第三步,在Program.cs中注册

 

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

 

 

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

 

 

 

 

 

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

 

 

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

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();

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

 

标签:----------------------------------------------------------------,jwtSecurityToke
From: https://www.cnblogs.com/lwx-99db/p/16732453.html

相关文章

  • .net6 使用 JWT
    安装Nuget包Microsoft.AspNetCore.Authentication.JwtBearerProgram.cs里添加JWT//添加jwt验证:builder.Services.AddAuthentication(JwtBearerDefaults.Authent......
  • .NET6 使用 AutoMapper (解析)
    一、Net6环境下的.netcore项目里如何使用AutoMapper实现依赖注入。注:AutoMapper是一个对象-对象映射器,可以将一个对象映射到另一个对象。第一步,在Nuget引入......
  • NetCore 生成JWT
    调用privatereadonlyIESP_UsersBLL_UsersBLL;privatereadonlyIConfiguration_configuration;privateJWTService_jwtService;......
  • JWT
      官网:https://jwt.io/  JWT是标准化的token,全称为JsonWebToken,是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准(RFC7519)  从本质上讲JWT也......
  • 淘宝API接口系列,获取购买到的商品订单列表,卖出的商品订单列表,订单详情,订单物流,买家信
    custom自定义API操作buyer_order_list获取购买到的商品订单列表buyer_order_detail获取购买到的商品订单详情buyer_order_express获取购买到的商品订单物流buyer_addr......
  • JWT:拥有我,即拥有权力
     Hi,这里是桑小榆。 上篇文章中,我们一起探讨了OAuth协议的原理以及授权认证流程,本次我们一起探讨jwt令牌作为授权协议的传输介质。OAuth协议规范了几个参与角色的......
  • fastapi_token权限管理和中间件
    token验证逻辑写在中间件里koa中的中间件的位置前端在header中发送token的处理token权限管理等级管理......
  • .net6 使用 AutoMapper
    引用AutoMapper.Extensions.Microsoft.Dependencylnjection包组织映射配置的一个好方法是使用配置文件。创建继承自Profile并将配置放入构造函数的类publicclassR......
  • .net6 使用 Autofac
    在Nuget引入Autofac、Autofac.Extensions.DependencyInjection定义Module,方便对注入服务进行管理publicclassAutoFacManager:Autofac.Module{//......
  • JsonWebToken
    (一)JsonWebToken是什么?JSONWebToken是一个开放标准协议,它定义了一种“紧凑”和“自包含”的方式,它用于各方之间作为JSON对象安全地传输信息。紧凑:数据量较少,并且能通过......