前言
現在前后端分離,基於session設計到跨越問題,而且session在多台服器之前同步問題,肯能會丟失,所以傾向於使用jwt作為token認證 json web token
- 導入java-jwt工具包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.15.0</version>
</dependency>
- 通過jwt生成token
編寫通用TokenService
package cn.soboys.core.authentication;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author kenx
* @version 1.0
* @date 2021/6/22 10:23
* token 操作
*/
@Service("TokenService")
public class TokenService {
//過期時間單位 毫秒 7*24*60*60*1000
private final Long tokenExpirationTime = 604800000l;
/**
* @param uuid 用戶唯一標示
* @param secret 用戶密碼等
* @return token生成
*/
public String generateToken(String uuid, String secret) {
//每次登錄充當前時間重新計算
Date expiresDate = new Date(System.currentTimeMillis() + tokenExpirationTime);
String token = "";
token = JWT.create()
//設置過期時間
.withExpiresAt(expiresDate)
//設置接受方信息,一般時登錄用戶
.withAudience(uuid)// 將 user id 保存到 token 里面
//使用HMAC算法
.sign(Algorithm.HMAC256(secret));// 以 password 作為 token 的密鑰
return token;
}
}
- 編寫注解過濾攔截需要登錄驗證的
controller
PassToken
用於跳過登錄驗證UserLoginToken
表示需要登錄驗證
package cn.soboys.core.authentication;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:21
* 跳過登錄驗證
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
package cn.soboys.core.authentication;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:22
* 需要登錄驗證
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
- 編寫業務異常
AuthenticationException
認證失敗拋出認證異常AuthenticationException
package cn.soboys.core.authentication;
import lombok.Data;
/**
* @author kenx
* @version 1.0
* @date 2021/6/22 13:58
* 認證異常
*/
@Data
public class AuthenticationException extends RuntimeException {
public AuthenticationException(String message) {
super(message);
}
}
- 編寫認證攔截器
AuthenticationInterceptor
,攔截需要認證請求
package cn.soboys.core.authentication;
import cn.hutool.extra.spring.SpringUtil;
import cn.soboys.core.ret.ResultCode;
import cn.soboys.mallapi.entity.User;
import cn.soboys.mallapi.service.IUserService;
import cn.soboys.mallapi.service.impl.UserServiceImpl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:24
* 用戶驗證登錄攔截
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
//從header中獲取token
public static final String AUTHORIZATION_TOKEN = "authorizationToken";
private IUserService userService= SpringUtil.getBean(UserServiceImpl.class);
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader(AUTHORIZATION_TOKEN);// 從 http 請求頭中取出 token
httpServletRequest.setAttribute("token", token);
// 如果不是映射到Controller mapping方法直接通過
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//檢查是否有passtoken注釋,有則跳過認證
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//檢查有沒有需要用戶權限的注解
//Annotation classLoginAnnotation = handlerMethod.getBeanType().getAnnotation(UserLoginToken.class);// 類級別的要求登錄標記
if (method.isAnnotationPresent(UserLoginToken.class) || handlerMethod.getBeanType().isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken =
method.getAnnotation(UserLoginToken.class) == null ?
handlerMethod.getBeanType().getAnnotation(UserLoginToken.class) : method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 執行認證
if (token == null) {
throw new AuthenticationException("無token,請重新登錄");
}
// 獲取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new AuthenticationException("非法用戶");
}
User user = userService.getUserInfoById(userId);
if (user == null) {
throw new AuthenticationException("用戶過期,請重新登錄");
}
// 驗證 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserMobile())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new AuthenticationException("非法用戶");
}
return true;
}
}
return true;
}
}