springboot跨域请求


CorsConfiguration相关属性说明
属性 说明
origins
允许的来源列表. 他的值放置在HTTP协议的响应header的Access-Control-Allow-Origin .
– – 意味着所有的源都是被允许的。
– 如果未定义,则允许所有来源。
allowedHeaders 实际请求期间可以使用的请求标头列表. 值用于预检的响应header Access-Control-Allow-Headers。
– – 意味着允许客户端请求的所有头文件。
– 如果未定义,则允许所有请求的headers。
methods 支持的HTTP请求方法列表。 如果未定义,则使用由RequestMapping注释定义的方法。
exposedHeaders 浏览器允许客户端访问的响应头列表。 在实际响应报头Access-Control-Expose-Headers中设置值。
– 如果未定义,则使用空的暴露标题列表。
allowCredentials 它确定浏览器是否应该包含与请求相关的任何cookie。
– false – cookies 不应该包括在内。
– "" (空字符串) – 意味着未定义.
– true – 预响应将包括值设置为true的报头Access-Control-Allow-Credentials。
– 如果未定义,则允许所有凭据。
maxAge 预响应的高速缓存持续时间的最大时间(以秒为单位)。 值在标题Access-Control-Max-Age中设置。
– 如果未定义, 最大时间设置为1800秒(30分钟)

方式一

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

  private CorsConfiguration buildConfig() {
    // 添加cors配置信息
    CorsConfiguration config = new CorsConfiguration();

    // 需要跨域的域名
    config.addAllowedOrigin("http://localhost:8080");

    // 设置允许请求的方式
    config.addAllowedMethod("*");

    // 设置允许的header
    config.addAllowedHeader("*");

    // 设置是否发送cookie信息
    config.setAllowCredentials(true);

    // 设置预响应的高速缓存持续时间的最大时间(以秒为单位,默认1800秒/30分钟)
    config.setMaxAge(1800L);

    return config;
  }

  @Bean
  public CorsFilter buildConfig() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 为url添加映射路径
    source.registerCorsConfiguration("/**", buildConfig());
    //返回重新定义好的source
    return new CorsFilter(source);
  }
}

方式二

public class CorsFilter extends OncePerRequestFilter {
 
    static final String ORIGIN = "Origin";
 
    protected void doFilterInternal(
        HttpServletRequest request, 
        HttpServletResponse response, 
        FilterChain filterChain) throws ServletException, IOException {
    
        String origin = request.getHeader(ORIGIN);
    
        response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");
    
        if (request.getMethod().equals("OPTIONS"))
            response.setStatus(HttpServletResponse.SC_OK);
        else 
            filterChain.doFilter(request, response);
    
    }
}

 方式三

以上两种方式都是全局配置的,spring提供了@CrossOrigin注解,使用@CrossOrigin注解可以精细配置到类和方法上

一.spring框架中使用@CrossOrigin注解方法级CORS

    Spring MVC提供了@CrossOrigin注解。 这个注释标注了注释的方法或类型,允许跨源请求。

    默认情况下,@CrossOrigin允许所有的来源,所有的头文件,@RequestMapping注解中指定的HTTP方法和30分钟的maxAge

1.1@CrossOrigin Class/Controller Level

@CrossOrigin(origins = "*", allowedHeaders = "*")
@Controller
public class HomeController
{
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

1.2@CrossOrigin at Method Level

@Controller
public class HomeController
{
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

1.3 @CrossOrigin Overridden at Method Level

homeInit()方法只能从域http://example.com访问。 其他方法在HomeController中将可以从所有域访问。

@Controller
public class HomeController
{
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

二.Spring框架全局CORS 配置

2.1Spring MVC CORS 使用WebMvcConfigurerAdapter配置

要为整个应用程序启用CORS,请使用WebMvcConfigurerAdapter 添加 CorsRegistry

@Configuration
@EnableWebMvc
public class CorsConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST");
    }
}

2.2Spring Boot CORS 使用WebMvcConfigurer配置

在spring boot应用程序中,建议只声明一个WebMvcConfigurer bean。

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

2.3CORS 使用Spring Security配置

要通过Spring安全性启用CORS支持,请配置CorsConfigurationSource bean并使用HttpSecurity.cors() 配置。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            //other config
    }
 
    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

参考链接:http://www.leftso.com/blog/303.html

 

posted on 2020-11-22 15:55  往事随风、  阅读(516)  评论(0编辑  收藏  举报

导航