在访问令牌URL中启用CORS - SPRING

时间:2018-02-25 09:58:52

标签: spring-mvc spring-security cors spring-security-oauth2

我正在制作一个简单的春季安全项目。我使用Angular作为前端。对于身份验证,我从后端调用访问令牌,但在春天没有任何CORS启用。我该如何启用CORS。这是获取访问令牌的代码

if(   (a!='' || b!='' || c!='')   &&   (a=='' || b=='' || c=='')   )
    alert('Please fill all elements');

2 个答案:

答案 0 :(得分:2)

启用CORS的XML配置是,

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans       
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/mvc  
   http://www.springframework.org/schema/mvc/spring-mvc.xsd">

  <mvc:annotation-driven />

  <mvc:cors>

    <mvc:mapping path="/api/**" allowed-origins="http://domain1.com, http://domain2.com"
                 allowed-methods="GET, PUT" allowed-headers="header1, header2, header3"
                 exposed-headers="header1, header2" allow-credentials="false" max-age="123" />

    <mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />

  </mvc:cors>

 </beans> 

答案 1 :(得分:1)

很抱歉,我不知道如何通过XML来实现,但在我的基于注释的配置中,CORS的启用方式如下:

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;    

@Configuration
public class WebApiConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedMethods(
                        HttpMethod.GET.name(),
                        HttpMethod.POST.name(),
                        HttpMethod.PUT.name(),
                        HttpMethod.PATCH.name(),
                        HttpMethod.HEAD.name(),
                        HttpMethod.DELETE.name()
               );
    }
}