zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    分层图最短路(DP思想) BZOJ2662 [BeiJing wc2012]冻结
    动态规划 BZOJ1925 地精部落
    线性DP SPOJ Mobile Service
    线性DP codevs2185 最长公共上升子序列
    数位DP POJ3208 Apocalypse Someday
    线性DP POJ3666 Making the Grade
    杨氏矩阵 线性DP? POJ2279 Mr.Young's Picture Permutations
    tarjan强连通分量 洛谷P1262 间谍网络
    树链剖分 BZOJ3589 动态树
    二分图 BZOJ4554 [Tjoi2016&Heoi2016]游戏
  • 原文地址:https://www.cnblogs.com/jadening/p/14019640.html
Copyright © 2011-2022 走看看