19

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();
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
J_Ocampo
  • 445
  • 1
  • 7
  • 18

1 Answers1

23

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

fetch(url, {
  mode: 'cors',
  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.

Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18
  • 1
    That did the trick! I didn't even think about it because my GETs work just fine like that. Is this something particular to POST responses? Thanks a million, by the way! – J_Ocampo Feb 04 '18 at 23:03
  • It should work the same way since the resolve promise receives a response object in both cases. I would need to see the code in order to guess why it works in that case. – Miguel Calderón May 15 '18 at 13:20
  • When using TypeScript, I got this error: `Object literal may only specify known properties, and 'crossDomain' does not exist in type 'RequestInit'.ts(2345)` – Manpreet Apr 23 '23 at 17:41
  • I've corrected the example code, should not throw now. – Miguel Calderón May 30 '23 at 08:31