导包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
先配置拦截器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public JwtInterceptor jwtInterceptor(){
return new JwtInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/users/login/**","/code/verify");
}
}
public class JwtInterceptor implements HandlerInterceptor {
@Resource
private UsersService usersService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从 http 请求头中取出 token
String token = request.getHeader("token");
Claims ss = JWTUtils.parseToken(token);
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
if (StringUtils.isBlank(token)) {
throw new RuntimeException("无token,请重新登录");
}
// 获取 token中的userId,根据userId查询数据库,检查用户是否存在
Integer id;
try {
id = (Integer) ss.get("id");
} catch (JWTDecodeException j) {
throw new RuntimeException("401");
}
Users user = usersService.getById(id);
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// System.out.println(user);
// 验证 token
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
// try {
// jwtVerifier.verify(token);
// } catch (JWTVerificationException e) {
// throw new RuntimeException("token失效,请重新登录");
// }
return true;
}
}
jwt代码(注意SECRET_KEY必须最少四位不然报错)
public class JWTUtils {
private static final String SECRET_KEY = "llll";
private static final long EXPIRATION_TIME = 30 * 60 * 1000; // 30 minutes
public static String generateToken(String username,Integer id) {
Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
Map<String,Object> claims = new HashMap<>();
claims.put("username",username);
claims.put("id",id);
String token = Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
return token;
}
public static Claims parseToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
return claims;
}
}