我的方式非主流,控制却可以更加灵活,喜欢的朋友,不妨花一点时间学习一下

jwt认证分为两部分,第一部分是加密解密,第二部分是灵活的应用于中间件,我的处理方式是将获取token放到api的一个具体的controller中,将发放token与验证分离,token的失效时间,发证者,使用者等信息存放到config中。

1.配置:

在appsettings.json中增加配置

"Jwt": {
"Issuer": "issuer",//随意定义
"Audience": "Audience",//随意定义
"SecretKey": "abc",//随意定义
"Lifetime": 20, //单位分钟
"ValidateLifetime": true,//验证过期时间
"HeadField": "useless", //头字段
"Prefix": "prefix", //前缀
"IgnoreUrls": [ "/Auth/GetToken" ]//忽略验证的url
}

2:定义配置类:

internal class JwtConfig
{
public string Issuer { get; set; }
public string Audience { get; set; } /// <summary>
/// 加密key
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// 生命周期
/// </summary>
public int Lifetime { get; set; }
/// <summary>
/// 是否验证生命周期
/// </summary>
public bool ValidateLifetime { get; set; }
/// <summary>
/// 验证头字段
/// </summary>
public string HeadField { get; set; }
/// <summary>
/// jwt验证前缀
/// </summary>
public string Prefix { get; set; }
/// <summary>
/// 忽略验证的url
/// </summary>
public List<string> IgnoreUrls { get; set; }
}

3.加密解密接口:

 public interface IJwt
{
string GetToken(Dictionary<string, string> Clims);
bool ValidateToken(string Token,out Dictionary<string ,string> Clims);
}

4.加密解密的实现类:

install-package System.IdentityModel.Tokens.Jwt

 public class Jwt : IJwt
{
private IConfiguration _configuration;
private string _base64Secret;
private JwtConfig _jwtConfig = new JwtConfig();
public Jwt(IConfiguration configration)
{
this._configuration = configration;
configration.GetSection("Jwt").Bind(_jwtConfig);
GetSecret();
}
/// <summary>
/// 获取到加密串
/// </summary>
private void GetSecret()
{
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes("salt");
byte[] messageBytes = encoding.GetBytes(this._jwtConfig.SecretKey);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
this._base64Secret= Convert.ToBase64String(hashmessage);
}
}
/// <summary>
/// 生成Token
/// </summary>
/// <param name="Claims"></param>
/// <returns></returns>
public string GetToken(Dictionary<string, string> Claims)
{
List<Claim> claimsAll = new List<Claim>();
foreach (var item in Claims)
{
claimsAll.Add(new Claim(item.Key, item.Value??""));
}
var symmetricKey = Convert.FromBase64String(this._base64Secret);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _jwtConfig.Issuer,
Audience = _jwtConfig.Audience,
Subject = new ClaimsIdentity(claimsAll),
NotBefore = DateTime.Now,
Expires = DateTime.Now.AddMinutes(this._jwtConfig.Lifetime),
SigningCredentials =new SigningCredentials(new SymmetricSecurityKey(symmetricKey),
SecurityAlgorithms.HmacSha256Signature)
};
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(securityToken);
}
public bool ValidateToken(string Token, out Dictionary<string, string> Clims)
{
Clims = new Dictionary<string, string>();
ClaimsPrincipal principal = null;
if (string.IsNullOrWhiteSpace(Token))
{
return false;
}
var handler = new JwtSecurityTokenHandler();
try
{
var jwt = handler.ReadJwtToken(Token); if (jwt == null)
{
return false;
}
var secretBytes = Convert.FromBase64String(this._base64Secret);
var validationParameters = new TokenValidationParameters
{
RequireExpirationTime = true,
IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
ClockSkew = TimeSpan.Zero,
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = this._jwtConfig.ValidateLifetime,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = this._jwtConfig.Audience,
ValidIssuer = this._jwtConfig.Issuer
};
SecurityToken securityToken;
principal = handler.ValidateToken(Token, validationParameters, out securityToken);
foreach (var item in principal.Claims)
{
Clims.Add(item.Type, item.Value);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}

5.定义获取Token的Controller:

在Startup.ConfigureServices中注入 IJwt

services.AddTransient<IJwt, Jwt>();//Jwt注入

[Route("[controller]/[action]")]
[ApiController]
public class AuthController : ControllerBase
{
private IJwt _jwt;
public AuthController(IJwt jwt)
{
this._jwt = jwt;
}
/// <summary>
/// getToken
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult GetToken()
{
if (true)
{
Dictionary<string, string> clims = new Dictionary<string, string>();
clims.Add("userName", userName);
return new JsonResult(this._jwt.GetToken(clims));
}
}
}

6.创建中间件:

 public class UseJwtMiddleware
{
private readonly RequestDelegate _next;
private JwtConfig _jwtConfig =new JwtConfig();
private IJwt _jwt;
public UseJwtMiddleware(RequestDelegate next, IConfiguration configration,IJwt jwt)
{
_next = next;
this._jwt = jwt;
configration.GetSection("Jwt").Bind(_jwtConfig);
}
public Task InvokeAsync(HttpContext context)
{
if (_jwtConfig.IgnoreUrls.Contains(context.Request.Path))
{
return this._next(context);
}
else
{
if (context.Request.Headers.TryGetValue(this._jwtConfig.HeadField, out Microsoft.Extensions.Primitives.StringValues authValue))
{
var authstr = authValue.ToString();
if (this._jwtConfig.Prefix.Length > )
{
authstr = authValue.ToString().Substring(this._jwtConfig.Prefix.Length+, authValue.ToString().Length -(this._jwtConfig.Prefix.Length+));
}
if (this._jwt.ValidateToken(authstr, out Dictionary<string, string> Clims))
{
foreach (var item in Clims)
{
context.Items.Add(item.Key, item.Value);
}
return this._next(context);
}
else
{
context.Response.StatusCode = ;
context.Response.ContentType = "application/json";
return context.Response.WriteAsync("{\"status\":401,\"statusMsg\":\"auth vaild fail\"}");
}
}
else
{
context.Response.StatusCode = ;
context.Response.ContentType = "application/json";
return context.Response.WriteAsync("{\"status\":401,\"statusMsg\":\"auth vaild fail\"}");
}
}
}
}

7.中间件暴露出去

 public static class UseUseJwtMiddlewareExtensions
{
/// <summary>
/// 权限检查
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseJwt(this IApplicationBuilder builder)
{
return builder.UseMiddleware<UseJwtMiddleware>();
}
}

8.在Startup.Configure中使用中间件:

app.UseJwt();

以1的配置为例:

除了请求 /auth/getToken 不需要加头信息外,其他的请求一律要求头信息中必须带着

userless:prefix (从Auth/GetToken中获取到的token)

再提供一个demo的下载链接

链接: https://pan.baidu.com/s/1tLpZ-HbZJPp37HQVWew8Rg 提取码: 7n9g

一些截图:

1,在需要认证的的控制器中不需要做任何操作,可以通过httpcontext.item拿到存入clims中的信息

2.startup截图

3.发放token

4.配置

简单测试

直接请求  无权限

带着token去请求api/values得到响应

这里的exp就是该token的失效时间(unti时间戳),可以定义一个配置来确定什么时候要去重新生成token,这个动作在中间件中进行(比如给头信息中带上ReToken)客户端下次就用ReToken中的Token重新进行访问,很容易就做到了对token的续期操作

.net core webapi jwt 更为清爽的认证 ,续期很简单的更多相关文章

  1. .net core webapi jwt 更为清爽的认证

    原文:.net core webapi jwt 更为清爽的认证 我的方式非主流,控制却可以更加灵活,喜欢的朋友,不妨花一点时间学习一下 jwt认证分为两部分,第一部分是加密解密,第二部分是灵活的应用于 ...

  2. .net core webapi jwt 更为清爽的认证 ,续期很简单(2)

    .net core webapi jwt 更为清爽的认证  后续:续期以及设置Token过期 续期: 续期的操作是在中间件中进行的,续期本身包括了前一个Token的过期加发放新的Token,所以在说续 ...

  3. 【转】ASP.NET Core WebAPI JWT Bearer 认证失败返回自定义数据 Json

    应用场景:当前我们给微信小程序提供服务接口,接口中使用了权限认证这一块,当我使用 JWT Bearer 进行接口权限认证的时候,返回的结果不是我们客户端想要的,其它我们想要给客户端返回统一的数据结构, ...

  4. 重新拾取:ASP.NET Core WebApi 使用Swagger支持授权认证

    园子里已经有很多.NET Core 集成Swagger的文章,但对于使用授权的介绍蛮少的. public static class SwaggerServiceExtensions { public ...

  5. .NET CORE WebAPI JWT身份验证

    一.appsettings.Json文件配置 配置JWT公用参数. 1 /*JWT设置*/ 2 "JwtSetting": { 3 "Issuer": &quo ...

  6. ASP.NET Core WebApi基于JWT实现接口授权验证

    一.ASP.Net Core WebApi JWT课程前言 我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再 ...

  7. ASP.NET Core WebAPI中使用JWT Bearer认证和授权

    目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...

  8. ASP.NET Core 基于JWT的认证(二)

    ASP.NET Core 基于JWT的认证(二) 上一节我们对 Jwt 的一些基础知识进行了一个简单的介绍,这一节我们将详细的讲解,本次我们将详细的介绍一下 Jwt在 .Net Core 上的实际运用 ...

  9. ionic + asp.net core webapi + keycloak实现前后端用户认证和自动生成客户端代码

    概述 本文使用ionic/angular开发网页前台,asp.net core webapi开发restful service,使用keycloak保护前台页面和后台服务,并且利用open api自动 ...

随机推荐

  1. 开启和连接mysql服务器(win10为例)

    1.windows图标右键,选择“计算机管理”: 2.展开左边的“ 服务和应用程序” 选项,点击“服务",找到 MySQL 服务器,点击左侧的 "启动",即可完成 MyS ...

  2. (45)zabbix报警媒介:SMS

    介绍 服务器安装串口GSM短信猫之后,zabbix可以使用它来发送短信通知给管理员,如下注意事项: 串行设备速度要与GSM猫相匹配(linux下默认为/dev/ttyS0),zabbix无法设置设置串 ...

  3. zabbix:告警、恢复消息次数

    之前zabbix配置告警,存在告警信息发送多次并且恢复信息也跟着发送多次了,导致企业微信流量不够用,没有找到恢复信息单独的设置项 动作中的步骤我个人理解为:1-5的意思是发送5条告警消息      3 ...

  4. 浏览器中如何获取想要的offsetwidth、、、clientwidth、、offsetheight、、、clientheight。。。

    clientWidth是对象看到的宽度(不含边线,即border)scrollWidth是对象实际内容的宽度(若无padding,那就是边框之间距离,如有padding,就是左padding和右pad ...

  5. Developing

    To work with the Android code, you will need to use both Git and Repo. In most situations, you can u ...

  6. lucene segment的产生,flush, commit与es的refresh,flush

    1 segment的产生 当索引一个文档时,如果存在空闲的segment(未被其他线程锁定),则取出空闲segment list中的最后一个segment(LIFO),并锁定,将文档索引至该segme ...

  7. Django之ORM操作(重要)

    Django ORM操作 一般操作 看专业的官网文档,做专业的程序员! 必知必会13条   <1> all(): 查询所有结果 <2> get(**kwargs): 返回与所给 ...

  8. SAXException Parser configuration problem: namespace reporting is not enabled

    问题描述: 用sax的方式组装xml,在tomcat上正常运行,在weblogic12c上报错: SAXException Parser configuration problem: namespac ...

  9. [android开发篇]activity组件篇

    https://developer.android.com/guide/components/activities.html Activity 是一个应用组件,用户可与其提供的屏幕进行交互,以执行拨打 ...

  10. 九度oj 1547

    题目描述: 给定一个初始为空的栈,和n个操作组成的操作序列,每个操作只可能是出栈或者入栈. 要求在操作序列的执行过程中不会出现非法的操作,即不会在空栈时执行出栈操作,同时保证当操作序列完成后,栈恰好为 ...