重点:配置拦截器的java文件必须和启动类放到一起
Interceptor ——》path patterns路径匹配规则
一个*:只匹配字符,不匹配路径(/)
两个**:匹配字符,和路径(/)
import java.util.List;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableAutoConfiguration
@Configuration
public class AuthInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("config coming..............");
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/api/mini/**")
.excludePathPatterns("/api/mini/auth/jsCode2Session",
"/api/mini/authc/",
"/api/mini/auth/*");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();// 自己写的拦截器
}
// 下面的暂时不需要
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
@Override
public void addFormatters(FormatterRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// TODO Auto-generated method stub
}
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
// TODO Auto-generated method stub
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
// TODO Auto-generated method stub
}
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
// TODO Auto-generated method stub
}
@Override
public Validator getValidator() {
// TODO Auto-generated method stub
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
// TODO Auto-generated method stub
return null;
}
}
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
UserApi _userApi;
@Autowired
AccessTokenApi _accessTokenApi;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object object) throws Exception {
//System.out.println("AuthenticationInterceptor coming..............");
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 执行认证
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 400);
if (token == null) {
token = httpServletRequest.getParameter("accessToken");
if (token == null) {
jsonObject.put("message", "无token,请重新登录");
sendError(jsonObject.toJSONString(), httpServletResponse);
return false;
}
}
AccessToken accessToken =_accessTokenApi.get(token);
if(accessToken == null || !_accessTokenApi.isValid(accessToken)) {
jsonObject.put("message", "token不存在或过期了,请重新登录");
sendError(jsonObject.toJSONString(), httpServletResponse);
return false;
}
String userId = accessToken.getUserId();
User user = _userApi.getByUserId(userId);
if (user == null) {
jsonObject.put("message", "用户不存在,请重新登录");
sendError(jsonObject.toJSONString(), httpServletResponse);
return false;
}
//验证通过,续期token
_accessTokenApi.renew(token);
return true;
}
private void sendError(String reason, HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json; charset=UTF-8");
response.getWriter().write(reason);
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}