這篇文章給大家分享的是有關(guān).net core webapi jwt認(rèn)證的示例分析的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
在五通橋等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專(zhuān)注、極致的服務(wù)理念,為客戶(hù)提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作按需網(wǎng)站設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),成都營(yíng)銷(xiāo)網(wǎng)站建設(shè),外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè),五通橋網(wǎng)站建設(shè)費(fèi)用合理。jwt認(rèn)證分為兩部分,第一部分是加密解密,第二部分是靈活的應(yīng)用于中間件,我的處理方式是將獲取token放到api的一個(gè)具體的controller中,將發(fā)放token與驗(yàn)證分離,token的失效時(shí)間,發(fā)證者,使用者等信息存放到config中。
1.配置:
在appsettings.json中增加配置
"Jwt": { "Issuer": "issuer",//隨意定義 "Audience": "Audience",//隨意定義 "SecretKey": "abc",//隨意定義 "Lifetime": 20, //單位分鐘 "ValidateLifetime": true,//驗(yàn)證過(guò)期時(shí)間 "HeadField": "useless", //頭字段 "Prefix": "prefix", //前綴 "IgnoreUrls": [ "/Auth/GetToken" ]//忽略驗(yàn)證的url }
2:定義配置類(lèi):
internal class JwtConfig { public string Issuer { get; set; } public string Audience { get; set; } ////// 加密key /// public string SecretKey { get; set; } ////// 生命周期 /// public int Lifetime { get; set; } ////// 是否驗(yàn)證生命周期 /// public bool ValidateLifetime { get; set; } ////// 驗(yàn)證頭字段 /// public string HeadField { get; set; } ////// jwt驗(yàn)證前綴 /// public string Prefix { get; set; } ////// 忽略驗(yàn)證的url /// public ListIgnoreUrls { get; set; } }
3.加密解密接口:
public interface IJwt { string GetToken(DictionaryClims); bool ValidateToken(string Token,out Dictionary Clims); }
4.加密解密的實(shí)現(xiàn)類(lèi):
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(); } ////// 獲取到加密串 /// 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); } } ////// 生成Token /// /// ///public string GetToken(Dictionary Claims) { List claimsAll = new List (); 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 Clims) { Clims = new Dictionary (); 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,//是否驗(yàn)證Issuer ValidateAudience = true,//是否驗(yàn)證Audience ValidateLifetime = this._jwtConfig.ValidateLifetime,//是否驗(yàn)證失效時(shí)間 ValidateIssuerSigningKey = true,//是否驗(yàn)證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(); // Jwt注入 [Route("[controller]/[action]")] [ApiController] public class AuthController : ControllerBase { private IJwt _jwt; public AuthController(IJwt jwt) { this._jwt = jwt; } /// /// getToken /// ///[HttpPost] public IActionResult GetToken() { if (true) { Dictionary clims = new Dictionary (); clims.Add("userName", userName); return new JsonResult(this._jwt.GetToken(clims)); } } }
6.創(chuàng)建中間件:
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 DictionaryClims)) { 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 { ////// 權(quán)限檢查 /// /// ///public static IApplicationBuilder UseJwt(this IApplicationBuilder builder) { return builder.UseMiddleware (); } }
8.在Startup.Configure中使用中間件:
app.UseJwt();
以1的配置為例:
除了請(qǐng)求 /auth/getToken 不需要加頭信息外,其他的請(qǐng)求一律要求頭信息中必須帶著
userless:prefix (從Auth/GetToken中獲取到的token)
感謝各位的閱讀!關(guān)于“.net core webapi jwt認(rèn)證的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!