Spring Boot CORS全局配置不适用于使用XMLHttpRequest登录

时间:2019-07-01 14:23:49

标签: spring spring-security xmlhttprequest

我制作了一个使用登录的简单API。这是我的安全配置:

       @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
.antMatcher("/**").authorizeRequests().anyRequest().authenticated()
                    .and()
                    .exceptionHandling()
                    .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
                    .and()
                    .httpBasic()
                    .and()
                    .formLogin()
                    .failureHandler(customAuthenticationFailureHandler)
                    .usernameParameter("email")
                    .passwordParameter("password")
                    .successHandler(authenticationSuccessHandler)
                    .and()
                    .csrf().disable()
            ;
        }

使用此WebMvcConfigurer:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/login")
                .allowedMethods("POST")
                .allowedOrigins("http://localhost:9000")
                .allowCredentials(true);
        registry
                .addMapping("/api/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(false);
    }
}

现在,使用POSTMAN或curl进行登录时不会出现任何问题:

$ curl -c cookie.txt -X POST -i -d "email=email@email.com" -d "password=1234567890" http://localhost:8080/login
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   317  100   268  100    49    268     49  0:00:01 --:--:--  0:00:01  2536
**HTTP/1.1 200**

但是当我尝试在此测试页上使用XMLHttpRequest时:

$(document).ready(function() {
    var data = null;

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log("xhr.status:"+xhr.status);
        console.log("this.responseText:"+this.responseText);
      }
    });

    var url = "http://localhost:8080/login";

    var params = 'email=email@email.com&password=1234567890';
    xhr.open('POST', url, true);

    //Send the proper header information along with the request
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader("cache-control", "no-cache");
    xhr.send(params);
});

此服务器在端口9000的Web服务器中运行。

但这是我得到的错误:

enter image description here

也要确定为什么spring尝试发送错误页面:

2019-07-01 08:17:35.069 DEBUG 1096 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for OPTIONS "/error", parameters={}
2019-07-01 08:17:35.070 DEBUG 1096 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public void org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$EmptyHandler.handle()
2019-07-01 08:17:35.071 DEBUG 1096 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 401

0 个答案:

没有答案