以下内容只是大概,具体业务要结合具体代码。
1.pom.xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2.拦截器类
public class JwtInterceptor extends HandlerInterceptorAdapter {
private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
boolean contains = contains(uri, "/user"); // 放行
// 自动排除生成token的路径,并且如果是options请求是cors跨域预请求,设置allow对应头信息
if (contains || RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
log.info("...自动排除生成token的路径...");
return true;
}
String token = request.getHeader("Authorization");
if (token == null || token.trim() == "") {
log.error("无法获取token.");
LineResult result = new LineResult();
result.setMsg("token is null");
result.setRet(1002);
SendMsgUtils.sendJsonMessage(response, result);
}
// 获取表中的token
log.info("获取到的token == {}", token);
try {
JwtUtils.checkToken(token);
return true;
} catch (Exception e) {
log.error("exception = {}", e.getMessage());
LineResult result = new LineResult();
result.setMsg(e.getMessage());
result.setRet(1003);
SendMsgUtils.sendJsonMessage(response, result);
}
return false;
}
private boolean contains(String uri, String... pattern) {
if (StringUtils.isEmpty(pattern)) {
return true;
} else {
for (String s : pattern) {
if (uri.contains(s)) {
return true;
}
}
}
return false;
}
}
3.把拦截器配置到系统中
@Configuration
public class SecurityConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
.addPathPatterns("/line") // 拦截的路径,拦截某个controller下所有接口/order/**
.excludePathPatterns("/*.js", "/*.png", "/*.css", "/*.html"); // 静态资源不需要拦截
}
}
4.JwtUtils工具类
public class JwtUtils {
final static String base64EncodedSecretKey = "base64EncodedSecretKey_test";// 私钥
/**
* 生成token
* @param userId
* @param tokenExp
* @return
*/
public static String getToken(String userId, long tokenExp) {
return Jwts.builder()
.setSubject(userId)
.claim("userId", userId)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + tokenExp)) // 过期时间
.signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
.compact();
}
/**
* 解析token
* @param token
* @throws ServletException
*/
public static void checkToken(String token) throws ServletException {
try {
final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
String userId = (String) claims.get("userId");
} catch (ExpiredJwtException e1) {
throw new ServletException("token expired");
} catch (Exception e) {
throw new ServletException("other token exception, e = " + e);
}
}
}
5.生成token,返回给前端
// tokenExp 从配置文件或者数据库取
log.info("jwt.token.exp ==== {}", tokenExp);
String token = JwtUtils.getToken(md5UserId, tokenExp);
result.put("token", token);
版权声明:本文为haidian_fengyu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。