一、JWT原理:
1、傳統的登錄方式:瀏覽器輸入用戶名密碼,服務器端檢驗通過後,根據用戶信息生成一個token,將token和userID存到數據庫或者session中,並將token返回給前端存入cookie。之後客戶端訪問時會帶上cookie中的信息,服務端根據客戶端提供的信息對比來驗證登錄的客戶有效性。
存在弊端:問題1:如果出現XSS(Cross-Site Scripting)跨站請求漏洞,由於cookie可以被js讀取,xss漏洞會導致用戶token被泄露。
解決辦法:設置HttpOnly,這樣的話Cookie將不會被JS讀取,避免了攻擊者僞造cookie的情況出現。(IIS設置方法:https://jingyan.baidu.com/article/54b6b9c0a5d1d22d583b4700.html)。或者設置secure,這樣cookie就只能通過https傳輸,可以過濾掉一些使用http協議請求的XSS注入。
但是問題2來了: XSRF/CSRF(Cross-site request forgery)跨站請求僞造,也被稱爲“One Click Attack”或者Session Riding。
解決辦法:CSRF攻擊的本質是通過僞造用戶的請求來通過驗證,用戶的一些信息保存在cookie中,黑客無法獲取用戶cookie的情況下,通過利用用戶自己的cookie來獲取頁面權限,從而達到攻擊目的。但是也可以解決,用戶登陸的時候由服務器發放一個隨機token給用戶,用戶每次發送請求的時候都帶上這個token,用戶請求中的token通過和服務端token對比,從而來驗證發送請求信息的用戶的有效性。防範CSRF要注意Token的保密性和隨機性。
還有個辦法也可以考慮,我發現銀行轉賬都有設置,根據HTTP協議,在HTTP頭中有一個字段叫Referer,它記錄了該HTTP請求的來源地址。在通常情況下,訪問一個安全受限的頁面的請求都來自於同一個網站。比如某銀行的轉賬是通過用戶訪問http://www.xxx.com/transfer
頁面完成的,用戶必須先登錄訪問到http://www.xxx.com/transfer
,然後通過單擊頁面上的提交按鈕來觸發轉賬事件。
總結,防止CSRF攻擊需要將cookie設置爲httponly,以及增加session相關的Hash token碼,最好在header中再加上Referer。
2、使用JWT的優勢
(1)可以通過URL POST參數或者在http header中發送,數據量小。
(2)負載Payload中包含了所有需要的信息,避免多次查詢數據庫
JWT的組成:HEADER.PAYLOAD.SIGNATURE
HEADER
包含token的元數據,主要是加密算法,和簽名的類型,如下面的信息,說明了加密的對象類型是JWT,加密算法是HMAC SHA-256。
{"alg":"HS256","typ":"JWT"}
然後需要通過BASE64編碼後存入token中
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload
主要包含一些聲明信息(claim),這些聲明是key-value對的數據結構。通常如用戶名,角色等信息,過期日期等,因爲是未加密的,所以不建議存放敏感信息。
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name":"admin","exp":1578645536,"iss":"webapi.cn","aud":"WebApi"}
也需要通過BASE64編碼後存入token中
eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9
Signature
jwt要符合jws(Json Web Signature)的標準生成一個最終的簽名。把編碼後的Header和Payload信息加在一起,然後使用一個強加密算法,如 HmacSHA256,進行加密。HS256(BASE64(Header).Base64(Payload),secret)
2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4
最後生成的token如下
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4
下面切入主題
開發環境:netCore3.1,之前文章有寫過一些系統搭建的基礎,喜歡的老鐵可以去看看之前的文章來搭建基礎服務。
使用NPM包管理安裝Microsoft.AspNetCore.Authentication.JwtBearer。
創建一個簡單的POCO類,用來存儲簽發或者驗證JWT時用到的信息。
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Webapi.Models
{
public class TokenManagement
{
[JsonProperty("secret")]
public string Secret { get; set; }
[JsonProperty("issuer")]
public string Issuer { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("accessExpiration")]
public int AccessExpiration { get; set; }
[JsonProperty("refreshExpiration")]
public int RefreshExpiration { get; set; }
}
}
然後在 appsettings.Development.json
增加jwt使用到的配置信息(如果是生成環境在appsettings.json
添加即可)
"tokenManagement": {
"secret": "123456",
"issuer": "webapi.cn",
"audience": "WebApi",
"accessExpiration": 30,
"refreshExpiration": 60
}
然後再startup類的ConfigureServices方法中增加讀取配置信息
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllers();
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
}
到目前爲止,我們完成了一些基礎工作,下面再webapi中注入jwt的驗證服務,並在中間件管道中啓用authentication中間件。
startup類中要引用jwt驗證服務的命名空間
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
然後在ConfigureServices
方法中添加如下邏輯
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
再Configure
方法中啓用驗證
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
//app.UseDeveloperExceptionPage();
//}
//app.UseHttpsRedirection();
app.UseAuthentication();
//app.UseRouting();
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
//endpoints.MapControllers();
//});
}
上面完成了JWT驗證的功能,下面就需要增加簽發token的邏輯。我們需要增加一個專門用來用戶認證和簽發token的控制器,命名成AuthenticationController
,同時增加一個請求的DTO類
public class LoginRequestDTO
{
[Required]
[JsonProperty("username")]
public string Username { get; set; }
[Required]
[JsonProperty("password")]
public string Password { get; set; }
}
[ApiVersion("1")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
[AllowAnonymous]
[HttpPost, Route("requestToken")]
public ActionResult RequestToken([FromBody] LoginRequestDTO request)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request");
}
return Ok();
}
}
目前上面的控制器只實現了基本的邏輯,下面我們要創建簽發token的服務,去完成具體的業務。第一步我們先創建對應的服務接口,命名爲IAuthenticateService
public interface IAuthenticateService
{
bool IsAuthenticated(LoginRequestDTO request, out string token);
}
接下來,實現接口
public class TokenAuthenticationService : IAuthenticateService
{
public bool IsAuthenticated(LoginRequestDTO request, out string token)
{
throw new NotImplementedException();
}
}
在Startup
的ConfigureServices
方法中註冊服務
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
在Controller中注入IAuthenticateService服務,並完善action
public class AuthenticationController : ControllerBase
{
private readonly IAuthenticateService _authService;
public AuthenticationController(IAuthenticateService authService)
{
this._authService = authService;
}
[AllowAnonymous]
[HttpPost, Route("requestToken")]
public ActionResult RequestToken([FromBody] LoginRequestDTO request)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request");
}
string token;
if (_authService.IsAuthenticated(request, out token))
{
return Ok(token);
}
return BadRequest("Invalid Request");
}
}
正常情況,我們都會根據請求的用戶和密碼去驗證用戶是否合法,需要連接到數據庫獲取數據進行校驗,我們這裏爲了方便,假設任何請求的用戶都是合法的。
這裏單獨加個用戶管理的服務,不在IAuthenticateService這個服務裏面添加相應邏輯,主要遵循了職責單一原則
。首先和上面一樣,創建一個服務接口IUserService
public interface IUserService
{
bool IsValid(LoginRequestDTO req);
}
實現IUserService
接口
public class UserService : IUserService
{
//模擬測試,默認都是人爲驗證有效
public bool IsValid(LoginRequestDTO req)
{
return true;
}
}
同樣註冊到容器中
services.AddScoped<IUserService, UserService>();
接下來,就要完善TokenAuthenticationService簽發token的邏輯,首先要注入IUserService 和 TokenManagement,然後實現具體的業務邏輯,這個token的生成還是使用的Jwt的類庫提供的api,具體不詳細描述。
特別注意下TokenManagement的注入是已IOptions的接口類型注入的,還記得在Startpup中嗎?我們是通過配置項的方式註冊TokenManagement類型的。
public class TokenAuthenticationService : IAuthenticateService
{
private readonly IUserService _userService;
private readonly TokenManagement _tokenManagement;
public TokenAuthenticationService(IUserService userService, IOptions<TokenManagement> tokenManagement)
{
_userService = userService;
_tokenManagement = tokenManagement.Value;
}
public bool IsAuthenticated(LoginRequestDTO request, out string token)
{
token = string.Empty;
if (!_userService.IsValid(request))
return false;
var claims = new[]
{
new Claim(ClaimTypes.Name,request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials);
token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return true;
}
}
準備好測試試用的APi,打上Authorize特性,表明需要授權!
[ApiController]
[Route("[controller]")]
[Authorize]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
支持我們可以測試驗證了,我們可以使用postman來進行http請求,先啓動http服務,獲取url,先測試一個訪問需要授權的接口,但沒有攜帶token信息,返回是401,表示未授權
把Token複製出來(
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoic3RyaW5nIiwiZXhwIjoxNTg4MzI1NDI0LCJpc3MiOiJ3ZWJhcGkuY24iLCJhdWQiOiJXZWJBcGkifQ.wz0xUgsCi3Pe8IR5xm-ncGx0w_6bkEL02cOi_jXvT2Q
),加到網頁訪問請求裏面。
成功通過JWT訪問頁面