微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在本地主机上的Spring和Angular 2之间启用CORS

如何解决如何在本地主机上的Spring和Angular 2之间启用CORS

我在Spring 4.3.4.RELEASE和Spring安全性4.2.2.RELEASE上有一个带有Java后端的旧项目。无法更新库,我必须使用已有的库。该项目不是REST API,没有RestController或WebMvcConfigurer。因此,我按照建议的here配置了cors:

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    protected SecurityConfiguration() {
        super();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // we don't need CSRF because our token is invulnerable
                .csrf().disable()

                // don't create session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .authorizeRequests()

                // allow anonymous resource requests
                .antMatchers(HttpMethod.GET,"/","/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js")
                .permitAll()
                .antMatchers(HttpMethod.POST,"/rpc/*").permitAll()
                .anyRequest().permitAll();

        httpSecurity.addFilterBefore(new CorsFilter(),ChannelProcessingFilter.class);

        // disable page caching
        httpSecurity.headers().cacheControl();
    }
}

Cors过滤器:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws servletexception,IOException {
        logger.error("CORS filter: " + request.getmethod());
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With,xsrf-token");
        response.addheader("Access-Control-Expose-Headers","xsrf-token");
        if ("OPTIONS".equals(request.getmethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request,response);
        }
    }
}

在web.xml中,所有上下文参数之后且在listerenrs之前(这是应用程序中唯一的过滤器):

   <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>web.servlet.response.CorsFilter
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

我在localhost:8080上运行后端,在localhost:8081上运行前端 但是,当我尝试发送内部包含application / json的POST请求时,浏览器控制台出现错误

Access to XMLHttpRequest at 'http://localhost:8080/rpc' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

此外,我希望在后端看到日志“ CORS过滤器:POST”,我将其放在此处以检查是否可以进入过滤器,但没有此类日志。

请问关于它为什么不起作用的任何建议?我需要在请求中坚持使用application / json,并且有时在应用程序中还会有一个Authorization标头,因此无法完全避免cors。这可以是Angular 2问题吗?

解决方法

我不熟悉spring或java,但是我想我理解问题。

我认为您的日志记录过滤器不起作用,因为Spring框架会在执行过滤器之前使该请求短路。

这里的问题可能在配置中,但是我认为解决该问题的方法通常不正确。

CORS是出于某些目的而创建的,通过允许来自所有其他来源的浏览器发出请求,您实际上会造成一些潜在的安全问题。

理想情况下,如果服务器和客户端都是您的应用程序,则应仅从客户端向与客户端应用程序托管源相同的源发出请求。因此,在本地情况下,它应该向localhost:8081发出请求,可以通过在发出请求时省略客户端的主机基地址来实现。

要使其正常运行,对于开发环境而言,最好的选择是为角度设置代理(以代理从localhost:8081localhost:8080的请求),详细的设置信息为here。 / p>

对于生产环境,您需要在同一源上托管后端服务器/客户端应用程序。您可以通过在后端服务器/客户端Web服务器前放置一些代理服务器,或者直接在后端服务器上托管客户端应用(角度静态输出文件)来实现此目的。

另一种选择是执行您尝试做的事情,但不允许所有来源(不是.permitAll())的请求,而是-列出特定的允许来源(例如localhost:8081)。 但这不是那么干净,您还需要为开发环境和生产指定不同的来源。

,

此错误是由于拒绝OPTION Web方法导致的,因此应在configure方法中添加以下语句:

.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()

像这样:

httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()

            // allow anonymous resource requests
            .antMatchers(HttpMethod.GET,"/","/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js")
            .permitAll()
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
            .antMatchers(HttpMethod.POST,"/rpc/*").permitAll()
            .anyRequest().permitAll();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。