.NET6 JWT(生成Token令牌)
一、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();
----------------------------------------------------------------
.NET6 JWT(生成Token令牌)的更多相关文章
- .net core 基于Jwt实现Token令牌
Startup类ConfigureServices中 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJw ...
- 一、Core授权-2 之.net core 基于Jwt实现Token令牌
一.Startup类配置 ConfigureServices中 //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.Authenticati ...
- 国服最强JWT生成Token做登录校验讲解,看完保证你学会!
转载于:https://blog.csdn.net/u011277123/article/details/78918390 Free码农 2017-12-28 00:08:02 JWT简介 JWT(j ...
- 利用jwt生成token,用于http请求身份验证
前段时间在做移动端接口过程中,考虑到安全性,所有移动端发送请求(除了登录请求)过程中进行token有效验证. 1.利用jwt生成token a.导入jwt相关包 <!-- jwt --> ...
- 使用 JWT 生成 Token 代码示例
JSON Web Token,简称 JWT, 是一个开放的标准(RFC 7519),它定义了以一种紧凑的.自包含的 JSON 对象在各方之间安全传输信息的方式.该信息含有数字签名,可以被验证和信任. ...
- Token_使用JWT生成token
1.token三部分 header { "typ": "JWT", "alg": "HS256" } paylo ...
- JWT生成token及过期处理方案
业务场景 在前后分离场景下,越来越多的项目使用token作为接口的安全机制,APP端或者WEB端(使用VUE.REACTJS等构建)使用token与后端接口交互,以达到安全的目的.本文结合stacko ...
- tp5使用jwt生成token,做api的用户认证
首先 composer 安装 firebase/php-jwt github:https://github.com/firebase/php-jwt composer require firebas ...
- JWT生成token
1.JWT简介 JSON Web Token 简称JWT.一个JWT实际上就是一个字符串,它由三部分组成,头部.载荷与签名.JWT生成的token是这样的 2.Json Web Token(JWT)生 ...
随机推荐
- C#/VB.NET 添加多行文本水印到Word文档
一般情况下,在Word中添加文字水印仅支持添加一个文本字样的水印,但在复杂的办公环境中,由于对不同文档的设计要求,需要在Word文档中添加平铺水印效果,即文档中的水印文字以多行多列分布的形式存在.本文 ...
- DFS序和7种模型
DFS序就是将树的节点按照先根的顺序遍历得到的节点顺序 性质:一个子树全在一个连续的区间内,可以与线段树和树状数组搭配使用 很好写,只需在dfs中加几行代码即可. 代码: void dfs(ll u, ...
- Unity3D学习笔记10——纹理数组
目录 1. 概述 2. 详论 2.1. 实现 2.2. 注意 3. 参考 1. 概述 个人认为,纹理数组是一个非常有用的图形特性.纹理本质上是一个二维的图形数据:通过纹理数组,给图形数据再加上了一个维 ...
- Fibonacci Nim
目录 题意 题解 相关 Ref 题意 [COCI2010-2011#4] HRPA 取石子,但是: 先手第一次可取任意多个石子 此外每次可取的石子的个数,至少为 \(1\) ,至多为上一轮对方所取个数 ...
- React报错之`value` prop on `input` should not be null
正文从这开始~ 总览 当我们把一个input的初始值设置为null或者覆盖初始值设置为null时,会产生"valueprop on input should not be null" ...
- 解决beego运行程序报错问题:stderr: go: github.com/astaxie/beego@v1.12.1: missing go.sum entry
使用命令bee new beegodemo02创建beego程序后,使用VScode打开后,便会报错无法运行,报错信息如下: Error loading workspace: err: exit st ...
- React生命周期和响应式原理(Fiber架构)
注意:只有类组件才有生命周期钩子函数,函数组件没有生命周期钩子函数. 生命周期 装载阶段:constructor() render() componentDidMount() 更新阶段:render( ...
- Redis 18 Jedis
参考源 https://www.bilibili.com/video/BV1S54y1R7SB?spm_id_from=333.999.0.0 版本 本文章基于 Redis 6.2.6 概述 Jedi ...
- Redis 10 位图
参考源 https://www.bilibili.com/video/BV1S54y1R7SB?spm_id_from=333.999.0.0 版本 本文章基于 Redis 6.2.6 概述 Redi ...
- Git 07 IDEA集成Git
参考源 https://www.bilibili.com/video/BV1FE411P7B3?spm_id_from=333.999.0.0 版本 本文章基于 Git 2.35.1.2 IDEA 是 ...