使用Spring Security启用CORS Spring问题

时间:2016-06-29 02:45:54

标签: spring spring-security cors

我需要为使用Spring的{​​{1}}应用启用CORS,但它无效。我正在从Spring Security(即node.js服务器)向GET(即Tomcat服务器)发出http://localhost:3000请求。

我尝试了以下方法,但无法使其中任何一个工作: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

Spring Data Rest and Cors

https://gist.github.com/zeroows/80bbe076d15cb8a4f0ad

Enabling CORS using Spring Boot 1.3.3-RELEASE

Spring CORS controller annotation not working

目前我有http://localhost:8080

@Controller

@Controller @RequestMapping("/views") public class LoginController{ @Autowired private EventService eventService; @RequestMapping(value = "/companies", method = RequestMethod.GET, produces = "application/json") @ResponseBody public String listCompanies(Model model) { String companiesList = eventService.getCompanies(); return companiesList; } } 文件我尝试不允许AppConfig失败:

CORS

我想以某种方式从@EnableWebMvc @Configuration public class AppConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } } 应用中的json方法中获取listCompanies。我收到Angular2错误,因此我认为这是No 'Access-Control-Allow-Origin' header is present问题。

3 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,并使用自定义过滤器进行了修复,如文档中所述:27.5 Filter based CORS support

基本上,您需要创建过滤器:

public class MyCorsFilter extends CorsFilter {

    public MyCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

}

然后在springSecurityFilterChain之前将它添加到web.xml(或相应的基于java的配置)中:

<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>com.example.configuration.cors.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

我也有dispatchOptionsRequest(根据新文档没有必要):

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    ...
    <!-- "OPTIONS" method support -->
    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>
    ...
</servlet>

答案 1 :(得分:0)

您是否在弹簧配置中定义了允许的原点? http://localhost:8080

@EnableWebMvc 
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("http://localhost:3000")
        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
        .allowCredentials(true);
    }
}

查看官方文档的第27.3章以启用全局CORS配置: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html

如果您不需要在跨源请求中加入Cookie,请将.allowCredentials(true)替换为.allowCredentials(false)

答案 2 :(得分:0)

   import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Enabling CORS support  - Access-Control-Allow-Origin
 * 
 * 
 * <code>
    <!-- Add this to your web.xml to enable "CORS" -->
    <filter>
      <filter-name>cors</filter-name>
      <filter-class>com.elm.mb.rest.filters.CORSFilter</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>cors</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
 * </code>
 */
public class CORSFilter extends OncePerRequestFilter {
    private static final Log LOG = LogFactory.getLog(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");

        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            LOG.trace("Sending Header....");
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//          response.addHeader("Access-Control-Allow-Headers", "Authorization");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1");
        }

        filterChain.doFilter(request, response);
    }

}