@Configuration
public class Loginconfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
// 添加拦截器路径
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 放行登录和注册
registry.addInterceptor(loginInterceptor).excludePathPatterns("/login","/register");
}
}
重写方法WebMvcConfigurer 的添加拦截器addInterceptors,添加拦截的路径。
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 拦截器检查是否有token
String token = request.getHeader("Authorization");
Map<String,Object> map = JwtUtil.parseToken(token);
Integer userid = (Integer) map.get("id");
try{
// 根据前端token获取redis的token
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
String RedisToken = stringStringValueOperations.get(userid.toString());
if (RedisToken==null)
{
throw new RuntimeException();
}
// 放行
Map<String, Object> UsertMap = JwtUtil.parseToken(token);
// 把含有用户名字的信息放进线程池
ThreadLocalUtil.set(UsertMap);
return true;
}catch (Exception e){
// 不放行
response.setStatus(401);
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
ThreadLocalUtil.remove();
}
拦截器中主要功能是先去检查客户端页面是否有token信息,从前端的request.getHeader(“Authorization”);获取得到token信息。使用JwtUtil工具类解析得到用户信息。
public class JwtUtil {
private static final String KEY = "lcc练习jwt";
//接收业务数据,生成token并返回
public static String genToken(Map<String, Object> claims) {
return JWT.create()
.withClaim("claims", claims)
.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
.sign(Algorithm.HMAC256(KEY));
}
//接收token,验证token,并返回业务数据
public static Map<String, Object> parseToken(String token) {
return JWT.require(Algorithm.HMAC256(KEY))
.build()
.verify(token)
.getClaim("claims")
.asMap();
}
}
上段是工具类,在pom文件导入以下依赖
<!-- jwt参数校验-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.3.0</version>
</dependency>
这里stringRedisTemplate是pom文件导入的依赖
<!-- Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>