18

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();
}
4
  • Post your spring security configuration
    – luboskrnac
    Feb 1, 2018 at 12:19
  • Added it to the post, is that the config you meant?
    – J_Ocampo
    Feb 1, 2018 at 12:24
  • Does your controller allow CORS? You need to specifically annotate a controller to allow CORS, I believe, with @CrossOrigin(origins = "http://localhost:9000") as an example.
    – cbll
    Feb 1, 2018 at 12:34
  • Yes, my controllers do: @CrossOrigin(origins = "localhost:3000")
    – J_Ocampo
    Feb 1, 2018 at 12:39

1 Answer 1

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.

4
  • 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 4, 2018 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. May 15, 2018 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 at 17:41
  • I've corrected the example code, should not throw now. May 30 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.