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;
}
}