Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Fetch in React with CORS

I'm completely new to CORS and i'm having the following issue:

-I'm using create-react-app (port 3000) that invokes some REST Services made in spring boot (port 8080). I added JWT auth to my REST API so now i have to authenticate before i call anything else.

Thing is, i can authenticate in my SpringBoot project index.html (which i used to test the jwt auth), but now that i call the /auth POST on React, i get a 200 OK but i cant seem to find the Token anywhere in the response.

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();
            },....

React Fetch (port 3000) with CORS

    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)
.....

While the react fetch returns a 200 OK, i get a fussy response and cant seem to get the responseJson.token the same way that i did without CORS. What am i missing?

Response:

Response {type: "cors", url: "http://localhost:8080/auth", redirected: false, status: 200, ok: true, …}

Any help is welcome.

Thanks in advance. Jorge

EDIT:

@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();
}
like image 724
J_Ocampo Avatar asked Feb 01 '18 12:02

J_Ocampo


1 Answers

You should convert the fetch response first with .json(). It returns a promise, so you can use it this way:

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) {
...

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

like image 97
Miguel Calderón Avatar answered Sep 21 '22 03:09

Miguel Calderón