惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
GRAHAM CLULEY
T
Tenable Blog
Know Your Adversary
Know Your Adversary
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
S
Security Affairs
NISL@THU
NISL@THU
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
Webroot Blog
Webroot Blog
Schneier on Security
Schneier on Security
S
SegmentFault 最新的问题
S
Schneier on Security
G
Google Developers Blog
V
V2EX
C
Check Point Blog
U
Unit 42
Google DeepMind News
Google DeepMind News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
T
The Exploit Database - CXSecurity.com
Recent Announcements
Recent Announcements
M
MIT News - Artificial intelligence
S
Secure Thoughts
博客园 - 司徒正美
Recorded Future
Recorded Future
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
K
Kaspersky official blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
博客园 - 聂微东
N
News and Events Feed by Topic
SecWiki News
SecWiki News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
Recent Commits to openclaw:main
Recent Commits to openclaw:main
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
Project Zero
Project Zero
W
WeLiveSecurity
博客园 - Franky

博客园 - James.H.Fu

PMS-授权中心 如何从现有版本1.4.8升级到element UI2.0.11 Maven私有仓库: 发布release版本报错:Return code is: 400, ReasonPhrase: Repository does not allow upd ating assets: maven-releases. spring boot + dubbo开发遇到过的异常 java,javascript中的url编码 SpringBoot favicon.ico SpringBoot 异常处理 在centos 7上安装BIMServer maven 单独构建多模块项目中的单个模块 MongoDB 安装及副本集简单操作 spring-boot dubbo项目使用docker方式部署 Spring Boot和Dubbo整合 springboot 定制错误页面 Maven私有仓库-使用docker部署Nexus - James.H.Fu - 博客园 centos7 sentry部署指南 静态文件服务器部署指南 开始使用ansible 2016项目开发经验总结及后续计划 - James.H.Fu - 博客园 2016工作总结
spring boot 跨域请求
James.H.Fu · 2017-09-25 · via 博客园 - James.H.Fu

场景

网站localhost:56338要访问网站localhost:3001的服务

在网站localhost:3001中增加CORS相关Java Config

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}

在网站localhost:56338中测试

@section Scripts{ 
    <script>
        $.ajax({
            method: "GET",
            url: "http://localhost:3001/api/project/getProjectInfo/50",
            headers: {
                'x-auth-token':'5136E8DD7D4AFCA77FDA3A4B4541A7FB88609FCFF1C0E9C2BC0060A3DBBB14E08F9B107336A218A62C247618BBF759312653BD70E4CEDAE86D285C8D459490728B008383929E8262CB40C9B0E8C841F3531E61F01FE71A937820176D45D348CE7C375D7020B8191A0190C46A318859C6'
            },
            xhrFields: {
                withCredentials: true
            }
        }).done(function (resp) {
            console.log(resp);
        }).fail(function () {

        }).always(function () {

        });
    </script>
}

备注

  1. 在使用过程中发现,有时可能不能正常实现跨域,原因是spring bean注册顺序的问题,所以一定要在配置上增加 @Order(Ordered.HIGHEST_PRECEDENCE), 保证它优先注册。
  2. 如果客户端需要带上cookie,需要增加withCredentials, vuejs, angularjs,ractjs上的设置方法要进一步研究一下。

参考资料

完整的WebConfig代码

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

//    @Bean
//    public FilterRegistrationBean corsFilter() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.setAllowCredentials(true);
//        config.addAllowedOrigin("*");
//        config.addAllowedHeader("*");
//        config.addAllowedMethod("*");
//        config.setMaxAge(3600L);
//        source.registerCorsConfiguration("/api/**", config);
//        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//        // 这个顺序很重要哦,为避免麻烦请设置在最前
//        bean.setOrder(0);
//        return bean;
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

}

“年轻人不要怕表现,要敢于出来表现,但还是那句话,要有正确的度,你的表现是分析问题和解决问题的能力。”

– 《你凭什么做好互联网》