dotNET Core 3.X 使用 Jwt 实现接口认证
在前后端分離的架構(gòu)中,前端需要通過 API 接口的方式獲取數(shù)據(jù),但 API 是無狀態(tài)的,沒有辦法知道每次請(qǐng)求的身份,也就沒有辦法做權(quán)限的控制。如果不做控制,API 就對(duì)任何人敞開了大門,只要拿到了接口地址就可以進(jìn)行調(diào)用,這是非常危險(xiǎn)的。本文主要介紹下在 dotNET Core Web API 中使用 Jwt 來實(shí)現(xiàn)接口的認(rèn)證。
Jwt 簡介
Jwt 的全稱是 JSON Web Token,是目前比較流行的接口認(rèn)證解決方案。有了 Jwt 后,從客戶端請(qǐng)求接口的流程如下圖:
客戶端發(fā)送用戶名密碼信息到認(rèn)證服務(wù)器獲取 token;
客戶端請(qǐng)求 API 獲取數(shù)據(jù)時(shí)帶上 token;
服務(wù)器端驗(yàn)證 token,合法則返回正確的數(shù)據(jù)。
有一個(gè)網(wǎng)站叫:https://jwt.io/ ,我們?cè)谶@個(gè)站點(diǎn)上對(duì) Jwt 產(chǎn)生的 token 做驗(yàn)證:
從上圖可以看出 Jwt 生產(chǎn)的 token 由三個(gè)部分組成:
Header(紅色):頭
Playload(紫色):負(fù)載
Verify Sigantuer(藍(lán)色):簽名
這三個(gè)部分由英文的點(diǎn)進(jìn)行分隔開
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoib2VjMjAwMyIsInNpdGUiOiJodHRwOi8vZndoeXkuY29tIiwiaWF0IjoxNTE2MjM5MDIyfQ.DYgo4eEUwlYJqQoLvAuFPxFRVcCow77Zyl2byaK6UxkHeader
頭信息是一個(gè) Json 格式的數(shù)據(jù)
{"alg":?"HS256","typ":?"JWT" }alg:表示加密的算法
typ:表示 token 的類型
Playload
Playload 是 token 的主體內(nèi)容部分,我們可以用來傳遞一些信息給客戶端,比如過期時(shí)間就是通過 Playload 來進(jìn)行傳遞的。但因?yàn)槟J(rèn)情況下 Playload 的數(shù)據(jù)是明文的,所以敏感信息不要放在這里。
Verify Sigantuer
Verify Sigantuer 是對(duì)前面兩個(gè)部分的簽名,防止數(shù)據(jù)篡改。
使用 Jwt
下面一步步介紹在 dotNET Core Web API 項(xiàng)目中使用 Jwt:
添加 Jwt 的包引用
在 Web API 項(xiàng)目中添加對(duì) Microsoft.AspNetCore.Authentication.JwtBearer 包的引用
修改 Starup
1、在 ConfigureServices 方法中添加服務(wù)注冊(cè)。
//?jwt?認(rèn)證 JwtSettings?jwtSettings?=?new?JwtSettings(); services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings")); Configuration.GetSection("JwtSettings").Bind(jwtSettings);services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o=>{o.TokenValidationParameters?=?new?Microsoft.IdentityModel.Tokens.TokenValidationParameters(){ValidateIssuerSigningKey?=?true,ValidIssuer?=?jwtSettings.Issuer,ValidAudience?=?jwtSettings.Audience,//用于簽名驗(yàn)證IssuerSigningKey?=?new?SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.SecretKey)),ValidateIssuer?=?false,ValidateAudience?=?false};});JwtSettings 的配置設(shè)置在 appsettings.json 配置文件中:
2、在 Configure 方法中添加對(duì)中間件的使用。
app.UseAuthentication(); app.UseAuthorization();添加認(rèn)證接口
添加 AuthorizeController 控制器:
[ApiController] public?class?AuthorizeController:?BaseController {private?readonly?IUserService?_userService;private?readonly?JwtSettings?_jwtSettings;public?AuthorizeController(IMapper?mapper,IUserService?userService,IOptions<JwtSettings>?options)?:?base(mapper){_userService?=?userService;_jwtSettings?=?options.Value;}///?<summary>///??獲取?token///?</summary>///?<param?name="request"></param>///?<returns></returns>[HttpPost]public?string?Token(TokenDto?request){bool?isValidate?=?_userService.ValidatePassword(request.UserName,?request.Password);if(!isValidate)?return?string.Empty;var?claims?=?new?Claim[]{new?Claim(ClaimTypes.Name,request.UserName)};var?key?=?new?SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));var?creds?=?new?SigningCredentials(key,?SecurityAlgorithms.HmacSha256);var?token?=?new?JwtSecurityToken(_jwtSettings.Issuer,_jwtSettings.Audience,claims,DateTime.Now,DateTime.Now.AddSeconds(10),creds);return?new?JwtSecurityTokenHandler().WriteToken(token);} }上面代碼中使用 IOptions 來做強(qiáng)類型配置,將 JwtSettings 配置類注入到該控制器中使用,關(guān)于更多配置內(nèi)容可以參考:《dotNET Core 配置》。
使用 Postman 測(cè)試
1、在需要進(jìn)行認(rèn)證的控制器或接口方法上添加 [Authorize] 標(biāo)記。
2、調(diào)用接口 http://localhost:5000/api/Authorize/token 獲取 token。
3、在請(qǐng)求接口時(shí)使用 Authorization 的方式使用 token,token 的類型為 Bearer Token ,可以看到帶上 token 后,數(shù)據(jù)正常返回。
在 Vue 中調(diào)用
前端技術(shù)有很多種,在這里以 Vue 為例,Vue 中處理 Jwt 有以下幾個(gè)步驟:
1、請(qǐng)求接口時(shí)判斷 localStorage 中是否有 token 數(shù)據(jù),沒有 token 數(shù)據(jù)或者 token 已經(jīng)過期,需要重新調(diào)用接口獲取新的 token;
2、使用 axios 的攔截器,在所有請(qǐng)求的 Header 中都添加 Authorization。
示例代碼:
Vue:https://github.com/oec2003/vue-jwt-demo
接口:https://github.com/oec2003/DotNetCoreThreeAPIDemo
希望本文對(duì)您有所幫助。
總結(jié)
以上是生活随笔為你收集整理的dotNET Core 3.X 使用 Jwt 实现接口认证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样实现WPF Prism Module
- 下一篇: 【半译】两个gRPC的C#库:grpc-