首页 > 其他分享 >.NET6 设置JWT

.NET6 设置JWT

时间:2023-08-25 20:11:07浏览次数:31  
标签:---------------------------------------------------------------- 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/weiyibo/p/17657830.html

相关文章

  • VMware16 设置中文的方法
    问题描述起初刚安装vmware16时,界面显示的英文解决方法在目标上面也就是.exe的后面添加--localeZH_CN注意:这里的--localeZH_CN在.exe后面要空一格,在locale后面空一格成功效果展示中文显示成功......
  • django配置swagger自动生成接口文档以及自定义参数设置
    首先安装swagger所用的包pipinstalldrf-yasg然后再settings.py中注册app     接口采用的token认证,在settings.py配置认证方式SWAGGER_SETTINGS={'USE_SESSION_AUTH':False,'SECURITY_DEFINITIONS':{......
  • Nacos-服务实例的权重设置
       一般可以应用在版本升级这种需要停掉服务器的服务上......
  • 设置反编译
    安装插件,有如下两种方法  A.将net.sf.jadclipse_3.2.4.jar复制到D:\leaf\eclipse\plugins目录下。  B.在d:\leaf下建立ecliplsePlungin\jadclipse\eclipse\plugins目录,将net.sf.jadclipse_3.2.4.jar放到该目录。在d:\leaf\eclipse\links下建jadclipse.link,内容为path=d\:\\lea......
  • .NET6 使用AutoMapper
    一、Net6环境下的.netcore项目里如何使用AutoMapper实现依赖注入。注:AutoMapper是一个对象-对象映射器,可以将一个对象映射到另一个对象。第一步,在Nuget引入AutoMapper、AutoMapper.Extensions.DependencyInjection这两个NuGet包  第二步,定义Profile,方便......
  • C#设置光标cur
    在resource文件中置入cur文件privateconstuintOCR_NORMAL=32512;[DllImport("user32.dll")]privatestaticexternboolSetSystemCursor(IntPtrhcur,uintid);[DllImport("user32.dll")]privatestaticexternboolSystemParametersInfo(uintuiAct......
  • 如何在leangoo免费敏捷工具中批量设置成员权限
    ​Leangoo领歌是一款永久免费的专业敏捷开发管理工具,提供端到端敏捷研发管理解决方案,涵盖敏捷需求管理、任务协同、进展跟踪、缺陷管理、统计度量等。包括小型团队敏捷开发,规模化敏捷SAFe,ScrumofScrums大规模敏捷。其功能/解决问题的价值包括:1)能够支持多种场景,如:敏捷研发管理......
  • Hue时间参数设置
    Oozie常用的系统常量常量使用公式含义说明${coord:minutes(intn)}返回日期时间:从一开始,周期执行n分钟${coord:hours(intn)}返回日期时间:从一开始,周期执行n*60分钟${coord:days(intn)}返回日期时间:从一开始,周期执行n*24*60分钟${coord:months(intn......
  • tomcat9中设置jks证书和pfx证书
    jks证书设置server.xml<Connectorport="443"protocol="org.apache.coyote.http11.Http11NioProtocol"maxThreads="1000"connectionTimeout="30000"maxPostSize="-1"enabl......
  • Docker 安装Redis 无法使用配置文件设置密码问题
    背景最近开发需要使用各种组件,如果都到开发机上安装,会占用电脑资源较多。所以使用docker容器来安装这些组件。例如redis、mongodb、mysql、rabitmq、elasticsearch等等。遇到的问题用edis官方镜像启动容器后,发现没有加载配置文件。解决方案1.redis镜像拉下来......