开发在线法律咨询平台的设计与实现Day3
今日完成
登录整合redis
导入依赖
<!-- redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
拦截器整合redis,再每次访问时都会去拿前端的token和redis中的token进行比对,若一致才可访问。
LoginInterceptor.java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
try{
//从redis中获取token
String redisToken = stringRedisTemplate.opsForValue().get(token);
//判断redis中的token是否过期
if(redisToken == null ){
throw new Exception("token过期");
}
// 解析token
Map<String,Object> claims = JwtUtil.parseToken(token);
ThreadLoaclUtil.set(claims);
return true;
}catch (Exception e){
response.setStatus(401);
return false;
}
}
再每次登录时,都会把token存到redis中
UserServiceImpl.java
//把token存在redis中
stringRedisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);