AngularJS + Spring Boot
在Spring REST API和客户端(AngularJS SPA)之间发出POST请求时出现以下错误:
XMLHttpRequest无法加载http://localhost:8080/users/insert。没有 '访问控制允许来源'标题出现在请求的上 资源。起源' http://localhost:9000'因此是不允许的 访问。响应的HTTP状态代码为403。
但问题是我添加了一个标题,允许来自此来源的请求。我做错了什么?
@Configuration
public class CORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (httpServletRequest.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(httpServletRequest.getMethod())) {
httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:9000");
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, Accept, X-Requested-With");
httpServletResponse.addHeader("Access-Control-Max-Age", "3600");
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
事实证明我的标头没有设置 - 在我的安全配置中禁用CSRF允许设置标头。以下是否有任何突出的错误?
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject private CustomUserDetailsService customUserDetailsService;
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.DELETE, "/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/**").hasRole("USER")
.antMatchers(HttpMethod.PUT, "/**").hasRole("USER")
.antMatchers(HttpMethod.GET, "/**").permitAll()
.and().csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
}
@Bean
protected CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
@Override
protected UserDetailsService userDetailsService() {
return customUserDetailsService;
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}