新增跨域配置

This commit is contained in:
wenc000 2020-03-12 18:33:57 +08:00
parent 3d86c6f36f
commit b6c312835b
2 changed files with 17 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package com.cm.common.wechat.config;
import com.cm.common.wechat.config.pojo.WechatOfficialAccountProperties;
import com.cm.common.wechat.filter.WechatFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -20,6 +21,9 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class WechatFilterConfig {
@Value(value = "${open-platform.wechat.apiCrossOrigin}")
private Boolean apiCrossOrigin;
@Autowired
private WechatOfficialAccountProperties wechatOfficialAccountProperties;
@ -27,6 +31,7 @@ public class WechatFilterConfig {
public FilterRegistrationBean wechatFilterRegister() {
WechatFilter wechatFilter = new WechatFilter();
wechatFilter.setWechatOfficialAccountProperties(wechatOfficialAccountProperties);
wechatFilter.setApiCrossOrigin(apiCrossOrigin);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(wechatFilter);

View File

@ -41,6 +41,7 @@ public class WechatFilter implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(WechatFilter.class);
private WechatOfficialAccountProperties wechatOfficialAccountProperties;
private Boolean apiCrossOrigin;
private AntPathMatcher antPathMatcher;
private static final String WECHAT_LOGIN_URL = "/**/wechat/sign/login";
@ -74,6 +75,13 @@ public class WechatFilter implements Filter {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (apiCrossOrigin != null && apiCrossOrigin) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
String requestUri = request.getRequestURI();
boolean isRelease = antPathMatcher.match(WECHAT_LOGIN_URL, requestUri)
|| antPathMatcher.match(WECHAT_RELEASE_URL, requestUri)
@ -209,6 +217,10 @@ public class WechatFilter implements Filter {
this.wechatOfficialAccountProperties = wechatOfficialAccountProperties;
}
public void setApiCrossOrigin(Boolean apiCrossOrigin) {
this.apiCrossOrigin = apiCrossOrigin;
}
/**
* 错误返回
*