React with CORS中的抓取问题

J_O*_*mpo 7 javascript fetch cors reactjs spring-boot

我对CORS完全陌生,遇到以下问题:

-我正在使用create-react-app(端口3000),该应用程序调用在Spring Boot(端口8080)中进行的一些REST服务。我将JWT身份验证添加到我的REST API中,因此现在我必须先进行身份验证,然后再调用其他任何内容。

事情是,我可以在SpringBoot项目index.html(用于测试jwt auth)中进行身份验证,但是现在我在React上调用了/ auth POST,我得到了200 OK,但我似乎无法在任何地方找到令牌在回应中。

SpringBoot index.html

function doLogin(loginData) {
        $.ajax({
            url: "/auth",
            type: "POST",
            data: JSON.stringify(loginData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                setJwtToken(**data.token**); //I can get the token without a problem
                $login.hide();
                $notLoggedIn.hide();
                showTokenInformation();
                showUserInformation();
            },....
Run Code Online (Sandbox Code Playgroud)

使用CORS进行React Fetch(端口3000)

    fetch(url, {
      crossDomain:true,
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({
        username: user,
        password: pass,
      })
    }).then((responseJson) => {
      console.log(responseJson);
      const tokenInfo = this.state.token;

      if(tokenInfo !== undefined)
.....
Run Code Online (Sandbox Code Playgroud)

虽然react fetch返回200 OK,但我得到的是一个挑剔的响应,似乎无法像没有CORS一样获得responseJson.token。我想念什么?

响应:

Response {type: "cors", url: "http://localhost:8080/auth", redirected: false, status: 200, ok: true, …}
Run Code Online (Sandbox Code Playgroud)

欢迎任何帮助。

提前致谢。乔治

编辑:

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

            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

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

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

            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
                    ,"/rates/**"
            ).permitAll()
            //Allows the user to authenticate
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity
            .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity
            .headers()
            .frameOptions().sameOrigin()
            .cacheControl();
}
Run Code Online (Sandbox Code Playgroud)

Mig*_*rón 11

您应该先使用转换获取响应.json()。它返回一个promise,因此您可以通过以下方式使用它:

fetch(url, {
  crossDomain:true,
  method: 'POST',
  headers: {'Content-Type':'application/json'},
  body: JSON.stringify({
    username: user,
    password: pass,
  })
})
  .then(response => response.json())
  .then(responseJson => {
    console.log(responseJson);
    const tokenInfo = this.state.token;
    if (tokenInfo !== undefined) {
...
Run Code Online (Sandbox Code Playgroud)

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch