Spring Boot CORS 403请求的资源上没有“Access-Control-Allow-Origin”标头

时间:2017-05-09 15:40:41

标签: spring security spring-boot cors

我正在学习使用Spring Boot 1.5.2作为服务器和angularJS 1.6作为客户端开发RESTful应用程序。当我尝试使用“localhost:8080 / login”从“localhost:9000 / login”登录时,我会收到403响应。

  

XMLHttpRequest无法加载http://localhost:8080/login。没有   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://127.0.0.1:9000”   访问。响应的HTTP状态代码为403。

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

import org.apache.catalina.filters.*;
import org.apache.catalina.filters.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.sql.DataSource;

@Order(1)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().and()
                .authorizeRequests()
                .antMatchers("/", "/home", "/login", "logout", "/customers").permitAll()
                .anyRequest().authenticated().and()
                .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
                .cors()
                    .disable();
    }


    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setSessionAttributeName("_csrf");
        return repository;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
class SimpleCORSFilter implements javax.servlet.Filter {

    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, HEAD, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, z-requested-with, X-Requested-With, Authorization, Content-Type, Access-Control-Allow-Origin");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

如何正确设置spring boot安全性,以便在没有CORS和CSRF问题的情况下使用angularJS?

2 个答案:

答案 0 :(得分:0)

您需要在Web安全筛选器之前按正确顺序添加筛选器,如下所示:

.addFilterBefore(
    new LoginFilter(new SimpleCORSFilter()),
    UsernamePasswordAuthenticationFilter.class
)

答案 1 :(得分:0)

@CrossOrigin(origins = "**", maxAge = 3600)

可以解决问题,但我认为这不是一个非常可靠的解决方案。到目前为止,我发现我的某些端点可以使用它,而某些端点仍在提供CORS错误。 尽管如此,对于大型项目,我仍然是一个快速技巧,我认为设置CORSFilters是必经之路,我相信这是您正在尝试做的事情。