0👍
You will need to enable CORS for your Spring Security filter chain and provide an @Bean
such as this example:
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addAllowedOrigin("http://127.0.0.1:4200");
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return source;
}
}
Note: Port 4200
is for an Angular development environment, replace with your Vue dev server port.
0👍
Thank you Steve!
I added the following code
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
//
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return urlBasedCorsConfigurationSource;
}
and in my ajax call I have to add mode: ‘no-cors’,
const url = 'http://127.0.0.1:9000/oauth2/token';
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append("redirect_uri", "http://127.0.0.1:9010/admin");
urlencoded.append("client_id", "utilo-client");
urlencoded.append("client_secret", "secret");
var requestOptions = {
method: 'POST',
mode: 'no-cors', // no-cors, *cors, same-origin
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://127.0.0.1:9000/oauth2/token", requestOptions)
.then((response) => {
return response.text();
})
.then((data) => {
console.log('data: ' + data); // is empty string???
})
.catch(error => console.log('error', error));
Now I no longer get error messages in the Javascript Console and also no more error messages in the Java Console.
But the response from the server is empty. When I test it with Postman I get a correct result. I don’t understand what’s wrong with that.
Source:stackexchange.com