zoukankan      html  css  js  c++  java
  • springboot设置cors跨域请求的两种方式

    1、第一种:

    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);
        
        }
    }
    @Bean
    public CorsFilter corsFilter() throws Exception {
        return new CorsFilter();
    }
    
    http
        .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
        .headers()
        .cacheControl();

    2、第二种:

    @Configuration
    public class CorsConfig {
        @Bean
        public FilterRegistrationBean corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            // 设置你要允许的网站域名,如果全允许则设为 *
            config.addAllowedOrigin("http://localhost:4200");
            // 如果要限制 HEADER 或 METHOD 请自行更改
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
            // 这个顺序很重要哦,为避免麻烦请设置在最前
            bean.setOrder(0);
            return bean;
        }
    }

    参考:

    jwt-spring-security-demo
    重拾后端之Spring Boot(五) -- 跨域、自定义查询及分页

    更新 2020-7-8

    由于使用了springboot 2.2.5.RELEASE和springcloud Hoxton.SR4,导致跨域写法有所变化,现更新如下:

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                // by default uses a Bean by the name of corsConfigurationSource
                .cors().and()
                ...
        }
    
        @Bean
        public CorsFilter corsFilter() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
            configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
            configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return new CorsFilter(source);
        }
    }
     

    或者

    @Configuration
    public class CorsConfig{
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.setAllowCredentials(true);
            return corsConfiguration;
        }
    
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", buildConfig());
            return new CorsFilter(source);
        }
    }

    总结

    1. 不能把上面的方法CorsFilter corsFilter()改成CorsConfigurationSource corsConfigurationSource(),因为我试了不起作用,提醒一下各位
    2. 我试了网上好多人的方法,但是只有上面的才起作用,分享给大家
  • 相关阅读:
    电信生命周期说明
    find in linux 2 微信公众号
    GDB中应该知道的几个调试方法 2 微信公众号
    linux 下程序员专用搜索源码用来替代grep的软件ack(后来发现一个更快的: rg), 且有vim插件的 2 微信公众号
    linux下的 c 和 c++ 开发工具及linux内核开发工具 2 微信公众号
    linux下命令行发送邮件的软件:mutt 微信公众号
    腺样体肿大的综合治疗考虑 微信公众号
    打呼噜治疗方法 微信公众号
    vim 操作 2 微信公众号
    nginx之外的web 服务器caddy 微信公众号
  • 原文地址:https://www.cnblogs.com/shoshana-kong/p/14269495.html
Copyright © 2011-2022 走看看