I'm trying to set up a login screen on my react app. This provides authorisation to my spring boot backend to provide the data I need displayed. However, I keep getting the following error message from Chrome:
Access to fetch at 'http://localhost:8102/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've tried the following and they don't seem to work:
In my React app:
Login.js
...
login = () => {
const user = {username: this.state.username, password: this.state.password};
fetch(SERVER_URL + "/login", {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
method: 'POST',
body: JSON.stringify(user)
})
.then(response => {
const jwtToken = response.headers.get("Authorization");
if(jwtToken != null) {
sessionStorage.setItem("jwt", jwtToken);
sessionStorage.setItem("username", this.state.username);
this.setState({ isAuthenticated: true });
} else {
this.setState({ open: true });
}
})
.catch(err => console.error(err));
}
...
In my App.js
:
class App extends Component {
constructor(props) {
super(props);
this.state = { user: "user" };
}
componentDidMount() {
fetch(USER_URL)
.then((response) => response.json())
.then((responseData) => { this.setState({ user: responseData._embedded.user }); })
.catch((err) => console.error("THIS IS A SERIOUS ERROR INDEED!" + err));
}
render() {
return(
<div className='App'>
<Login />
</div>
)
}
}
On my Spring Boot backend:
SecurityConfiguration.java
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and().addFilterBefore(new LoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
...
...
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
config.applyPermitDefaultValues();
source.registerCorsConfiguration("/**", config);
return source;
}
...
In my MainController.java1
@RestController
@CrossOrigin
public class MainController {
...
None of that seems to be properly working to get around this CORS issue.
My Server github repository is: AssetRegister-Server
My Client github repository is: AssetRegister-Client