前兩篇文章給大家介紹了在.NET Core中如何使用Swagger的文章,那今天給大家分享一下JWT
在做接口開發的同學可能都有感受,我的接口如何保護的問題,如果沒有身份驗證,那不是接口完全暴露在外面,任意使人調用,這顯然不是我們想要的一種結果。當然做身份驗證的方式有多種,今天給大家講一種比較流行了,標准的身份驗證JWT
什么是JWT?
隨着技術的發展,分布式web應用的普及,通過session管理用戶登錄狀態成本越來越高,因此慢慢發展成為token的方式做登錄身份校驗,然后通過token去取redis中的緩存的用戶信息,隨着之后jwt的出現,校驗方式更加簡單便捷化,無需通過redis緩存,而是直接根據token取出保存的用戶信息,以及對token可用性校驗,單點登錄更為簡單。
JWT的結構體是什么樣的?
JWT由三部分組成,分別是頭信息、有效載荷、簽名,中間以(.)分隔
(1)header(頭信息)
由兩部分組成,令牌類型(即:JWT)、散列算法(HMAC、RSASSA、RSASSA-PSS等)
(2)Payload(有效載荷)
JWT的第二部分是payload,其中包含claims。claims是關於實體(常用的是用戶信息)和其他數據的聲明,claims有三種類型: registered, public, and private claims。
Registered claims: 這些是一組預定義的claims,非強制性的,但是推薦使用, iss(發行人), exp(到期時間), sub(主題), aud(觀眾)等;
Public claims: 自定義claims,注意不要和JWT注冊表中屬性沖突
Private claims: 這些是自定義的claims,用於在同意使用這些claims的各方之間共享信息,它們既不是Registered claims,也不是Public claims。
(3)Signature
要創建簽名部分,必須采用編碼的Header,編碼的Payload,秘鑰,Header中指定的算法,並對其進行簽名。
JWT使用流程:
JWT在.NET Core項目中的具體用法:
(1)在ConfigureServices方法中添加JWT相關代碼:
#region 添加jwt驗證: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否驗證Issuer ValidateAudience = true,//是否驗證Audience ValidateLifetime = true,//是否驗證失效時間 ValidateIssuerSigningKey = true,//是否驗證SecurityKey ValidAudience = Configuration["audience"],//Audience ValidIssuer = Configuration["issuer"],//Issuer,這兩項和前面簽發jwt的設置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))//拿到SecurityKey }; }); #endregion
(2)在Configure方法中添加JWT代碼:
#region jwt app.UseAuthentication();//注意添加這一句,啟用驗證 #endregion
(3)創建一個JWT服務類:
public class JWTService { private readonly IConfiguration _configuration; public JWTService(IConfiguration configuration) { _configuration = configuration; } public string GetToken(string UserName) { var claims = new[] { new Claim(ClaimTypes.Name, UserName) }; //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token. /** * Claims (Payload) Claims 部分包含了一些跟這個 token 有關的重要信息。 JWT 標准規定了一些字段,下面節選一些字段: iss: The issuer of the token,token 是給誰的 sub: The subject of the token,token 主題 exp: Expiration Time。 token 過期時間,Unix 時間戳格式 iat: Issued At。 token 創建時間, Unix 時間戳格式 jti: JWT ID。針對當前 token 的唯一標識 除了規定的字段外,可以包含其他任何 JSON 兼容的字段。 * */ var token = new JwtSecurityToken( issuer: _configuration["issuer"], audience: _configuration["audience"], claims: claims, expires: DateTime.Now.AddHours(24), signingCredentials: creds); string returnToken = new JwtSecurityTokenHandler().WriteToken(token); return returnToken; } }
(4)在接口類或方法上標記身份驗證:
到此為止,JWT的基本用法就結束,非常簡單和方便,接下來我們用postman測試一下JWT是否生效:
(1)當我們在不登錄的情況下,訪問接口看看是什么現象:
我們發現接口返回提示:401 Unauthorized
(2)我們先調用登錄接口,先計算得到token,然后再來請求試試:
登錄成功后,接口返回了token值
(3)將token復制粘貼到下方,請求業務接口,成功調用: