0

Background: Have a react webapp on localhost:3000, spring boot backend on localhost:8080, and use OAuth2 from Google. The end goal is to log in through Oauth2 and retrieve said data from backend.

Issue: When I try perform a query I get the following error in console Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/v2/auth...&redirect_uri=http://localhost:8080/login/oauth2/code/google

Attempted Approaches: Disable CORS on spring (the config for it is below as what I currently have), change redirect URI to http://localhost:3000/oauth2/redirect, add some CORS filter from SO answers

SO questions I have used for attempted approaches: CORS support in spring boot and security (CORS Filter), No 'Access-Control-Allow-Origin' in Spring Boot + Spring Security + CORS (disable CORS)

Relevant Code: package.json (just proxy excerpt): "proxy": "http://localhost:8080/" App.js

class App extends Component {
  state = {
    clients: []
  };

  async componentDidMount() {
    const response = await fetch('/cmds');
    const body = await response.json();
    this.setState({clients: body});
  }

  render() {
    const {clients} = this.state;
    console.log(clients)
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <div className="App-intro">
              <h2>Clients</h2>
              {clients.map(client =>
                  <div key={client.description}>
                    {client.description} ({client.global.toString()})
                  </div>
              )}
            </div>
        </header>
      </div>
    );
  }
}

export default App;

(Spring) application.yml (client ID and secret removed from question)

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope:
              - email
              - profile
app:
  cors:
    allowedOrigins: http://localhost:3000,http://localhost:8080
  oauth2:
    authorizedRedirectUris:
      - http://localhost:3000/oauth2/redirect

SecurityConfig.java

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
        security.cors().and().csrf().disable();
        security
                .cors()
                .configurationSource(corsConfigurationSource())
                .and()
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
sirNikolai
  • 19
  • 2
  • You cannot allow credentials and use the wildcard. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards – jub0bs Feb 20 '22 at 09:30
  • @jub0bs I should've mentioned - tried that too (setting setAllowedOrigins to "http://localhost:3000"). Might be false train of thought but think it's more related to the fact that google auth doesn't sent back allowed CORS, not the backend – sirNikolai Feb 20 '22 at 13:57
  • did you find a solution? I am facing similar problem. – Ashish Mar 15 '22 at 12:22
  • @Ashish unfortunately not. I instead cut loses and rewrote the frontend in thymeleaf since the project was minimal enough. – sirNikolai Mar 20 '22 at 02:25
  • Yeah, seems like that is the only solution which exists on the internet if you want to handle oauth2 client from the spring. – Ashish Mar 20 '22 at 03:40

0 Answers0