Spring Boot跨域
程序员文章站
2022-06-06 19:39:09
...
addInterceptors拦截器和addCorsMappings跨域有冲突,不能写在一起,不然会有跨域问题。看以下代码:
@Configuration public class MvcConfig extends WebMvcConfigurerAdapter { // /** // * 跨域-有冲突 // * @param registry // */ // @Override // public void addCorsMappings(CorsRegistry registry) { // registry.addMapping("/**") // .allowedOrigins("*") // .allowCredentials(true) // .allowedHeaders("*") // .allowedMethods("GET", "POST", "DELETE", "PUT") // .maxAge(3600); // super.addCorsMappings(registry); // } @Override public void addInterceptors(InterceptorRegistry registry) { //注册自定义拦截器 {addPathPatterns-配置拦截的路径}、{excludePathPatterns-配置不拦截的路径} registry.addInterceptor(new InterceptorConfig()) .addPathPatterns("/api/user/**") .excludePathPatterns("/api/tourist/**"); super.addInterceptors(registry); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //Swagger安全性 registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } /** * jwt过滤器 * @return */ @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); JwtFilter filter = new JwtFilter(adminsService()); registrationBean.setFilter(filter); return registrationBean; } @Bean public IAdminsService adminsService() { return new AdminsServiceImpl(); } }
/** * 拦截器 * @author dwen * 2018年5月18日下午8:54:09 */ public class InterceptorConfig implements HandlerInterceptor { private static final Logger Logger = LoggerFactory.getLogger(InterceptorConfig.class); @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // Logger.info("===============afterCompletion=============="); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // Logger.info("===============postHandle=============="); } @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception { Logger.info("===============preHandle=============="); res.setHeader("Content-type", "text/html;charset=UTF-8"); res.setCharacterEncoding("UTF-8"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Allow-Headers", "*"); res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Content-Type", "application/json"); String url = req.getRequestURI(); String[] paths = url.split("/");//Get path userId ArrayList<String> pathList = new ArrayList<String>(Arrays.asList(paths)); String userIdStr = pathList.get(pathList.indexOf("user") + 1); int adminId = Integer.parseInt(userIdStr);//用户id String token = req.getHeader("x-access-token"); //【文件上传|导excel】不检查jwt if (url.contains("common/upload") || url.contains("importAutoSubjectExcel") || url.contains("importExaminationPlanExcel") || url.contains("importExaminationScoreExcel") || url.contains("importStudentInfoExcel") || url.contains("importStudyPlanExcel")) { return true; }else{ if (adminId > 0) { //TODO 检查jwt令牌, 如果令牌不合法或者过期 boolean result = JwtUtil.validateToken(token, userIdStr); if (!result) { res.getWriter().print(JSONUtils.returnJSON(null, Result.TOKEN_ERROR.key, Result.TOKEN_ERROR.value)); return false; } } } return true;//返回true继续向下执行,返回false取消当前请求 } }