springbootweb项目跨域访问处理笔记
解决springMVC web项目跨域访问问题
1、@CrossOrigin跨域注解
springboot自带跨域注解,可以放在RestController的类上或者方法上,还能自定义那些域名可以跨域,非常灵活
@CrossOrigin //默认情况下@CrossOrigin允许@RequestMapping注释中指定的所有源和HTTP方法
@CrossOrigin(origins = "*", allowedHeaders = "*")
@CrossOrigin(origins = "http://domain-2.com", allowedHeaders = "Access-Control-Allow-Headers, Content-Type, Accept, X-Requested-With, remember-me", maxAge = 3600)
2、过滤器方式
import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class MyCorsFilter implements Filter {
public MyCorsFilter() {
log.info(">>>>>> MyCorsFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getHeader("Origin") != null) {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
} else {
response.setHeader("Access-Control-Allow-Origin", "*");
}
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
3、在Web MVC Configuration的addCorsMappings方法中全局CORS配置
1)WebMvcConfigurationSupport
@Slf4j@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
super.addCorsMappings(registry);
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
}
}
2)WebMvcConfigurerAdapter
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");;
}
}
3)WebMvcConfigurer
@Slf4j
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
}
}
4)如果使用的是Spring Security,请确保在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
5)CorsConfiguration 和 CorsFilter
@Configurationpublic class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
或
@Beanpublic FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain-1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
可以轻松更改任何属性,并仅将此CORS配置应用于特定路径模式:
@Overridepublic void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain-2.com")
.allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
.allowedHeaders("header1","header2","header3")
.exposedHeaders("header1","header2")
.allowCredentials(false)
.maxAge(3600);
}
4、XML命名空间
可以使用mvc XML名称空间配置CORS 。
这种最小的XML配置在/**路径模式上启用CORS ,其默认属性与JavaConfig相同:
<mvc:cors> <mvc:mapping path="/**" />
</mvc:cors>
也可以使用自定义属性声明多个CORS映射:
<mvc:cors> <mvc:mapping path="/api/**"
allowed-origins="http://domain-1.com,http://domain-2.com"
allowed-methods="GET","POST","PUT","DELETE","OPTIONS"
allowed-headers="header1,header2,header3"
exposed-headers="header1,header2"
allow-credentials="false"
max-age="3600" />
<mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />
</mvc:cors>
以上是 springbootweb项目跨域访问处理笔记 的全部内容, 来源链接: utcz.com/z/515880.html