背景
系统之前为一个单页应用提供过Rest接口,部署时这个单页应用与系统不在同一域内,出现跨域无法访问的问题。Spring 从 4.2 版本开始提供了@CrossOrigin
注解,让这个问题的解决变得非常简单。
实现一
首先看下@CrossOrigin
的源码(删掉了开头的部分注释):
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.cors.CorsConfiguration;
/**
* @author Russell Allen
* @author Sebastien Deleuze
* @author Sam Brannen
* @since 4.2
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
String[] DEFAULT_ORIGINS = { "*" };
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
String[] DEFAULT_ALLOWED_HEADERS = { "*" };
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
boolean DEFAULT_ALLOW_CREDENTIALS = true;
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
long DEFAULT_MAX_AGE = 1800;
/**
* Alias for {@link #origins}.
*/
@AliasFor("origins")
String[] value() default {};
/**
* List of allowed origins, e.g. {@code "http://domain1.com"}.
* <p>These values are placed in the {@code Access-Control-Allow-Origin}
* header of both the pre-flight response and the actual response.
* {@code "*"} means that all origins are allowed.
* <p>If undefined, all origins are allowed.
* @see #value
*/
@AliasFor("value")
String[] origins() default {};
/**
* List of request headers that can be used during the actual request.
* <p>This property controls the value of the pre-flight response's
* {@code Access-Control-Allow-Headers} header.
* {@code "*"} means that all headers requested by the client are allowed.
* <p>If undefined, all requested headers are allowed.
*/
String[] allowedHeaders() default {};
/**
* List of response headers that the user-agent will allow the client to access.
* <p>This property controls the value of actual response's
* {@code Access-Control-Expose-Headers} header.
* <p>If undefined, an empty exposed header list is used.
*/
String[] exposedHeaders() default {};
/**
* List of supported HTTP request methods, e.g.
* {@code "{RequestMethod.GET, RequestMethod.POST}"}.
* <p>Methods specified here override those specified via {@code RequestMapping}.
* <p>If undefined, methods defined by {@link RequestMapping} annotation
* are used.
*/
RequestMethod[] methods() default {};
/**
* Whether the browser should include any cookies associated with the
* domain of the request being annotated.
* <p>Set to {@code "false"} if such cookies should not included.
* An empty string ({@code ""}) means <em>undefined</em>.
* {@code "true"} means that the pre-flight response will include the header
* {@code Access-Control-Allow-Credentials=true}.
* <p>If undefined, credentials are allowed.
*/
String allowCredentials() default "";
/**
* The maximum age (in seconds) of the cache duration for pre-flight responses.
* <p>This property controls the value of the {@code Access-Control-Max-Age}
* header in the pre-flight response.
* <p>Setting this to a reasonable value can reduce the number of pre-flight
* request/response interactions required by the browser.
* A negative value means <em>undefined</em>.
* <p>If undefined, max age is set to {@code 1800} seconds (i.e., 30 minutes).
*/
long maxAge() default -1;
}
从上面源码中可以看到,@CrossOrigin
注解支持用于类和方法,访问IP默认为不限制,预检请求的有效期默认为1800秒,所以如不需指定IP和有效期,直接给需要支持跨域的类或方法添加注解即可:
@CrossOrigin
public JSONObject myMethod(...) {
...
}
但是事情肯定不会这么简单。。。
实现二
真正的需求是要通过配置文件配置IP白名单,白名单内允许跨域访问。然鹅,由于注解的参数无法动态赋值,IP地址这种参数也不能硬编码,所以@CrossOrigin
就被我无情的抛弃了,转而通过Filter来实现:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "domainFilter")
public class DomainFilter implements Filter {
@Value("${allow-origin}")
private String domain;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (!domain.startsWith("http://") && !domain.startsWith("https://")) {
domain = "http://" + domain;
}
response.setHeader("Access-Control-Allow-Origin", domain);
response.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
在本类添加@ServletComponentScan
注解,或在Spring Boot启动类添加注解并配置参数覆盖到本类路径,即可生效。
别忘了在配置文件中添加配置项:
allow-origin=10.110.16.151