背景
Jwt
全稱是:json web token
。它將用戶信息加密到token
里,服務器不保存任何用戶信息。服務器通過使用保存的密鑰驗證token
的正確性,只要正確即通過驗證。
優點
- 簡潔: 可以通過
URL
、POST
參數或者在HTTP header
發送,因為數據量小,傳輸速度也很快; - 自包含:負載中可以包含用戶所需要的信息,避免了多次查詢數據庫;
- 因為
Token
是以JSON
加密的形式保存在客戶端的,所以JWT
是跨語言的,原則上任何web
形式都支持; - 不需要在服務端保存會話信息,特別適用於分布式微服務。
缺點
- 無法作廢已頒布的令牌;
- 不易應對數據過期。
一、Jwt
消息構成
1.1 組成
一個token
分3部分,按順序為
- 頭部(
header
) - 載荷(
payload
) - 簽證(
signature
)
三部分之間用.
號做分隔。例如:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxYzdiY2IzMS02ODFlLTRlZGYtYmU3Yy0wOTlkODAzM2VkY2UiLCJleHAiOjE1Njk3Mjc4OTF9.wweMzyB3tSQK34Jmez36MmC5xpUh15Ni3vOV_SGCzJ8
1.2 header
Jwt
的頭部承載兩部分信息:
- 聲明類型,這里是
Jwt
- 聲明加密的算法 通常直接使用
HMAC SHA256
Jwt
里驗證和簽名使用的算法列表如下:
JWS | 算法名稱 |
---|---|
HS256 | HMAC256 |
HS384 | HMAC384 |
HS512 | HMAC512 |
RS256 | RSA256 |
RS384 | RSA384 |
RS512 | RSA512 |
ES256 | ECDSA256 |
ES384 | ECDSA384 |
ES512 | ECDSA512 |
1.3 playload
載荷就是存放有效信息的地方。基本上填2
種類型數據
- 標准中注冊的聲明的數據;
- 自定義數據。
由這2部分內部做base64
加密。
- 標准中注冊的聲明 (建議但不強制使用)
iss: jwt簽發者
sub: jwt所面向的用戶
aud: 接收jwt的一方
exp: jwt的過期時間,這個過期時間必須要大於簽發時間
nbf: 定義在什么時間之前,該jwt都是不可用的.
iat: jwt的簽發時間
jti: jwt的唯一身份標識,主要用來作為一次性token,從而回避重放攻擊。
- 自定義數據:存放我們想放在
token
中存放的key-value
值
1.4 signature
Jwt
的第三部分是一個簽證信息,這個簽證信息由三部分組成base64
加密后的header
和base64
加密后的payload
連接組成的字符串,然后通過header
中聲明的加密方式進行加鹽secret
組合加密,然后就構成了Jwt
的第三部分。
二、Spring Boot
和Jwt
集成示例
示例代碼采用:
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.8.1</version> </dependency>
2.1 項目依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.8.1</version> </dependency> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>1.8.4</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> </dependencies>
2.2 自定義注解@JwtToken
加上該注解的接口需要登錄才能訪問
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface JwtToken { boolean required() default true; }
2.3 Jwt 認證工具類JwtUtil.java
主要用來生成簽名、校驗簽名和通過簽名獲取信息
public class JwtUtil { /** * 過期時間5分鍾 */ private static final long EXPIRE_TIME = 5 * 60 * 1000; /** * jwt 密鑰 */ private static final String SECRET = "jwt_secret"; /** * 生成簽名,五分鍾后過期 * @param userId * @return */ public static String sign(String userId) { try { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(SECRET); return JWT.create() // 將 user id 保存到 token 里面 .withAudience(userId) // 五分鍾后token過期 .withExpiresAt(date) // token 的密鑰 .sign(algorithm); } catch (Exception e) { return null; } } /** * 根據token獲取userId * @param token * @return */ public static String getUserId(String token) { try { String userId = JWT.decode(token).getAudience().get(0); return userId; } catch (JWTDecodeException e) { return null; } } /** * 校驗token * @param token * @return */ public static boolean checkSign(String token) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier verifier = JWT.require(algorithm) // .withClaim("username", username) .build(); DecodedJWT jwt = verifier.verify(token); return true; } catch (JWTVerificationException exception) { throw new RuntimeException("token 無效,請重新獲取"); } } }
2.4 攔截器攔截帶有注解的接口
JwtInterceptor.java
public class JwtInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) { // 從 http 請求頭中取出 token String token = httpServletRequest.getHeader("token"); // 如果不是映射到方法直接通過 if(!(object instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod=(HandlerMethod)object; Method method=handlerMethod.getMethod(); //檢查有沒有需要用戶權限的注解 if (method.isAnnotationPresent(JwtToken.class)) { JwtToken jwtToken = method.getAnnotation(JwtToken.class); if (jwtToken.required()) { // 執行認證 if (token == null) { throw new RuntimeException("無token,請重新登錄"); } // 獲取 token 中的 userId String userId = JwtUtil.getUserId(token); System.out.println("用戶id:" + userId); // 驗證 token JwtUtil.checkSign(token); } } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
- 注冊攔截器:
WebConfig.java
@Configuration public class WebConfig implements WebMvcConfigurer { /** * 添加jwt攔截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor()) // 攔截所有請求,通過判斷是否有 @JwtToken 注解 決定是否需要登錄 .addPathPatterns("/**"); } /** * jwt攔截器 * @return */ @Bean public JwtInterceptor jwtInterceptor() { return new JwtInterceptor(); } }
2.5 全局異常捕獲
@RestControllerAdvice public class GlobalExceptionHandler { @ResponseBody @ExceptionHandler(Exception.class) public Object handleException(Exception e) { String msg = e.getMessage(); if (msg == null || msg.equals("")) { msg = "服務器出錯"; } JSONObject jsonObject = new JSONObject(); jsonObject.put("message", msg); return jsonObject; } }
2.6 接口
JwtController.java
@RestController @RequestMapping("/jwt") public class JwtController { /** * 登錄並獲取token * @param userName * @param passWord * @return */ @PostMapping("/login") public Object login( String userName, String passWord){ JSONObject jsonObject=new JSONObject(); // 檢驗用戶是否存在(為了簡單,這里假設用戶存在,並制造一個uuid假設為用戶id) String userId = UUID.randomUUID().toString(); // 生成簽名 String token= JwtUtil.sign(userId); Map<String, String> userInfo = new HashMap<>(); userInfo.put("userId", userId); userInfo.put("userName", userName); userInfo.put("passWord", passWord); jsonObject.put("token", token); jsonObject.put("user", userInfo); return jsonObject; } /** * 該接口需要帶簽名才能訪問 * @return */ @JwtToken @GetMapping("/getMessage") public String getMessage(){ return "你已通過驗證"; } }
2.7 Postman
測試接口
2.7.1 在沒token
的情況下訪問jwt/getMessage
接口
- 請求方式:
GET
- 請求參數:無
- 請求地址:http://localhost:8080/jwt/getMessage
- 返回結果:
{
"message": "無token,請重新登錄"
}
2.7.2 先登錄,在訪問jwt/getMessage
接口
- 登錄請求及結果,詳見下圖:
登錄后得到簽名如箭頭處
- 在請求頭加上簽名,然后再請求
jwt/getMessage
接口
請求通過,測試成功!
2.7.3 過期后再次訪問
我們設置的簽名過期時間是五分鍾,五分鍾后再次訪問
jwt/getMessage
接口,結果如下:
通過結果,我們發現時間到了,簽名失效,說明該方案通過。