新建.net core web的api項目(.net core版本3.1)web
在Value控制器下寫一個模擬登陸接口,進行簡單的名字和密碼驗證便可。驗證經過後會返回一個token。api
1 [HttpGet] 2 [Route("api/login")] 3 public IActionResult Login(string userName,string pwd) 4 { 5 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd)) 6 { 7 var claims = new[] 8 { 9 new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") , 10 new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"), 11 new Claim(ClaimTypes.Name, userName) 12 }; 13 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey)); 14 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 15 var token = new JwtSecurityToken( 16 issuer: Const.Domain, 17 audience: Const.Domain, 18 claims: claims, 19 expires: DateTime.Now.AddMinutes(30), 20 signingCredentials: creds); 21 22 return Ok(new 23 { 24 token = new JwtSecurityTokenHandler().WriteToken(token) 25 }); 26 } 27 else 28 { 29 return BadRequest(new { message = "username or password is incorrect." }); 30 } 31 }
在login接口中的Const.Domain須要新建一個類Const.cs,用來保存密鑰app
1 public class Const 2 { 3 /// <summary> 4 /// 這裏爲了演示,寫死一個密鑰。實際生產環境能夠從配置文件讀取,這個是用網上工具隨便生成的一個密鑰 5 /// </summary> 6 public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"; 7 public const string Domain = "http://localhost:5000"; 8 }
在Startup.cs文件中添加JWT服務函數
1 public void ConfigureServices(IServiceCollection services) 2 { 3 4 #region JWT驗證 5 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 6 .AddJwtBearer(options => { 7 options.TokenValidationParameters = new TokenValidationParameters 8 { 9 ValidateIssuer = true,//是否驗證Issuer 10 ValidateAudience = true,//是否驗證Audience 11 ValidateLifetime = true,//是否驗證失效時間 12 ClockSkew = TimeSpan.FromSeconds(30), 13 ValidateIssuerSigningKey = true,//是否驗證SecurityKey 14 ValidAudience = Const.Domain,//Audience 15 ValidIssuer = Const.Domain,//Issuer,這兩項和前面簽發jwt的設置一致 16 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到SecurityKey 17 }; 18 }); 19 #endregion
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 20 }
在其後的Configure函數中添加啓動中間件工具
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); //開啓JWT驗證中間件 //.net core3比.net core2多加一個UseAuthentication,並且必須在UseAuthorization前面 //這是認證 app.UseAuthentication(); //這是受權 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
新建一個get接口用於測試JWT驗證是否成功測試
1 [HttpGet] 2 [Route("api/get")] 3 //JWT驗證標識 4 [Authorize] 5 public ActionResult<IEnumerable<string>> Get() 6 { 7 return new string[] { "value1", "value2" }; 8 }
打開PostMan測試登陸接口ui
複製登陸接口獲得的token,在Headers請求頭裏添加參數Authorization值爲Bearer+空格+tokenspa
當把Authorization去掉則會出現401狀態碼,無權限訪問.net