跨域配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
放开预检请求类型OPTIONS,或者直接注释取消拦截器
public class SecurityFilter implements Filter {
//将redis模板定义为其成员变量
private StringRedisTemplate redisTemplate;
//成员变量redis模板的set方法
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 过滤器拦截到请求执行的方法:
*/
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
/*
放开预检方法
*/
if("OPTIONS".equals(request.getMethod().toUpperCase())) {
// 允许OPTIONS请求通过
chain.doFilter(request, resp);
return;
}
//获取请求url接口
String path = request.getServletPath();
/*
白名单请求都直接放行:
*/
List<String> urlList = new ArrayList<>();
urlList.add("/captcha/captchaImage");
urlList.add("/login");
urlList.add("/logout");
//对上传图片的url接口/product/img-upload的请求直接放行
urlList.add("/product/img-upload");
//对static下的/img/upload中的静态资源图片的访问直接放行
if(urlList.contains(path)||path.contains("/img/upload")){
chain.doFilter(request, response);
return;
}
/*
其它请求都校验token:
*/
//拿到前端归还的token
String clientToken = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
//校验token,校验通过请求放行
if(StringUtils.hasText(clientToken)&&redisTemplate.hasKey(clientToken)){
chain.doFilter(request, response);
return;
}
//校验失败,向前端响应失败的Result对象转成的json串
Result result = Result.err(Result.CODE_ERR_UNLOGINED, "请登录!");
String jsonStr = JSON.toJSONString(result);
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(jsonStr);
out.flush();
out.close();
}
/*
直接注释上面的拦截器代码,取消拦截器
*/
// @Override
// public void init(FilterConfig filterConfig) throws ServletException {
// }
//
// @Override
// public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
// throws IOException, ServletException {
// chain.doFilter(req, resp);
// }
//
// @Override
// public void destroy() {
// }
}
部署时候遇到的问题,记忆一下