拦截器
package com.ydxy.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ydxy.common.utils.JwtUserUtils;
import com.ydxy.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
RedisTemplate<String, String> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// 如果是OPTIONS请求则结束
if (HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())) {
return true;
}
try{
String token = httpServletRequest.getHeader("J-Token");
// 检查token是否合法
JwtUtils.verify(token);
// 检查token是否注销
if(redisTemplate.keys(JwtUserUtils.LOGIN_TOKEN_PREFIX + "*:" + token).size() == 0) {
throw new Exception();
}
return true;
// }catch(ExpiredJwtException e) {
// // TODO
// return false;
}catch(Exception e){
httpServletResponse.setStatus(403);
httpServletResponse.sendError(403, "未授权的访问");
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
}
}
配置
package com.ydxy.config;
import org.springframework.beans.factory.annotation.Autowired;
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 JwtInterceptorConfig implements WebMvcConfigurer {
@Autowired
JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**").excludePathPatterns("/api/login/**", "/api/checkUpdate");
}
}
实现
WebMvcConfigurer
接口,而不是:
WebMvcConfigurerAdapter
已过时- 继承
WebMvcConfigurationSupport
,拦截器正常工作,但静态资源404
<mvc:interceptors>
<mvc:interceptor>
<!-- mapping 指定哪些url被拦截
/*表示根路径下的所有请求被拦截-/hello.do
/**表示根路径及其子路径下的所有请求被拦截/user/add.do
-->
<mvc:mapping path="/api/**"/>
<mvc:exclude-mapping path="/api/login/**"/>
<mvc:exclude-mapping path="/api/checkUpdate"/>
<!-- 配置拦截器的路径 -->
<bean class="com.ydxy.config.JwtInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>