.net core webapi jwt 更为清爽的认证详解
 更新时间:2019年05月26日 10:14:41   作者:FreeTimeWorker  

这篇文章主要介绍了.net core webapi jwt 更为清爽的认证详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

我的方式非主流,控制却可以更加灵活,喜欢的朋友,不妨花一点时间学习一下
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 > 0)
{
authstr = authValue.ToString().Substring(this._jwtConfig.Prefix.Length+1, authValue.ToString().Length -(this._jwtConfig.Prefix.Length+1));
}
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 = 401;
context.Response.ContentType = “application/json”;
return context.Response.WriteAsync(“{\\”status\\”:401,\\”statusMsg\\”:\\”auth vaild fail\\”}”);
}
}
else
{
context.Response.StatusCode = 401;
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:利用JWT如何实现对API的授权访问详解浅谈ASP.NET Core 中jwt授权认证的流程原理ASP.NET Core学习之使用JWT认证授权详解ASP.NET Core使用JWT认证授权的方法asp.net core集成JWT的步骤记录asp net core 2.1中如何使用jwt(从原理到精通)ASP.Net Core3.0中使用JWT认证的实现.NET core 3.0如何使用Jwt保护api详解Asp.Net Core基于JWT认证的数据接口网关实例代码.Net Core官方JWT授权验证的全过程

.net
core
webapi
jwt
认证

相关文章
asp.net Page.Controls对象(找到所有服务器控件)通过此对象找到所有服务器控件。 2008-11-11
jQuery实现倒计时跳转的例子这篇文章主要介绍了jQuery实现倒计时跳转的例子,需要的朋友可以参考下 2014-05-05
C# 定义常量 两种实现方法在C#中定义常量的方式有两种,一种叫做静态常量(Compile-time constant),另一种叫做动态常量(Runtime constant) 2012-11-11
页面编码codepage=936和65001的区别这篇文章主要介绍了页面编码codepage=936和65001的区别,需要的朋友可以参考下 2015-07-07
.NET Core结合Nacos实现配置加解密的方法当我们把应用的配置都放到配置中心后,很多人会想到这样一个问题,配置里面有敏感的信息要怎么处理呢?本文就详细的介绍了.NET Core Nacos配置加解密,感兴趣的可以了解一下 2021-06-06
ASP.NET C#生成下拉列表树实现代码下拉列表树很方便且时尚的一个导航,貌似很多的朋友都想实现这样一个列表树,本文将满足你们的设想,通过本文你们可以学到如何使用c#生成下拉列表树,感兴趣的你可不要错过了啊 2013-02-02
在Asp.net网页上写读Cookie的两种不同语法介绍asp.net开发时,为了存储一些信息通常是Session与Cookie同时使用,本文将会补充一下Cookie相关的资料,感兴趣的朋友可以了解一下在网页上写读Cookie的实现,希望本文对你有所帮助 2013-01-01
SignalR Self Host+MVC等多端消息推送服务(三)这篇文章主要为大家详细介绍了SignalR Self Host+MVC等多端消息推送服务的第三篇,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 2017-06-06
Asp.net在线备份、压缩和修复Access数据库示例代码这篇文章主要介绍了Asp.net如何在线备份、压缩和修复Access数据库,需要的朋友可以参考下 2014-03-03
.Net 对于PDF生成以及各种转换的操作这篇文章主要介绍了.Net 对于PDF生成以及各种转换的操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 2020-06-06

最新评论

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。