Jwt
全稱是:json web token
。它將用戶信息加密到token
裏,服務器不保存任何用戶信息。服務器經過使用保存的密鑰驗證token
的正確性,只要正確即經過驗證。java
URL
、POST
參數或者在HTTP header
發送,由於數據量小,傳輸速度也很快;Token
是以JSON
加密的形式保存在客戶端的,因此JWT
是跨語言的,原則上任何web
形式都支持;Jwt
消息構成一個token
分3部分,按順序爲git
header
)payload
)signature
)三部分之間用.
號作分隔。例如:github
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxYzdiY2IzMS02ODFlLTRlZGYtYmU3Yy0wOTlkODAzM2VkY2UiLCJleHAiOjE1Njk3Mjc4OTF9.wweMzyB3tSQK34Jmez36MmC5xpUh15Ni3vOV_SGCzJ8
複製代碼
Jwt
的頭部承載兩部分信息:web
Jwt
HMAC SHA256
Jwt
裏驗證和簽名使用的算法列表以下:redis
JWS | 算法名稱 |
---|---|
HS256 | HMAC256 |
HS384 | HMAC384 |
HS512 | HMAC512 |
RS256 | RSA256 |
RS384 | RSA384 |
RS512 | RSA512 |
ES256 | ECDSA256 |
ES384 | ECDSA384 |
ES512 | ECDSA512 |
載荷就是存放有效信息的地方。基本上填2
種類型數據算法
由這2部份內部作base64
加密。spring
iss: jwt簽發者
sub: jwt所面向的用戶
aud: 接收jwt的一方
exp: jwt的過時時間,這個過時時間必需要大於簽發時間
nbf: 定義在什麼時間以前,該jwt都是不可用的.
iat: jwt的簽發時間
jti: jwt的惟一身份標識,主要用來做爲一次性token,從而回避重放攻擊。
複製代碼
token
中存放的key-value
值Jwt
的第三部分是一個簽證信息,這個簽證信息由三部分組成 base64
加密後的header
和base64
加密後的payload
鏈接組成的字符串,而後經過header
中聲明的加密方式進行加鹽secret
組合加密,而後就構成了Jwt
的第三部分。數據庫
Spring Boot
和Jwt
集成示例示例代碼採用:json
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.1</version>
</dependency>
複製代碼
<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>
複製代碼
@JwtToken
加上該註解的接口須要登陸才能訪問springboot
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JwtToken {
boolean required() default true;
}
複製代碼
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 無效,請從新獲取");
}
}
}
複製代碼
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();
}
}
複製代碼
@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;
}
}
複製代碼
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 "你已經過驗證";
}
}
複製代碼
Postman
測試接口token
的狀況下訪問jwt/getMessage
接口GET
{
"message": "無token,請從新登陸"
}
複製代碼
jwt/getMessage
接口登陸後獲得簽名如箭頭處
jwt/getMessage
接口請求經過,測試成功!
咱們設置的簽名過時時間是五分鐘,五分鐘後再次訪問
jwt/getMessage
接口,結果以下:
經過結果,咱們發現時間到了,簽名失效,說明該方案經過。
關注公衆號,瞭解更多: