In my problem I have Spring Boot Application (which is using Spotify API) on backend and Vue application on front. I use server on localhost:8080 and front on localhost:8081. I want to connect my frontend to my backend via axios and I try everything and still get CORS error.
When I call test GET endpoint /getList() I' ve got
Access to XMLHttpRequest at 'http://localhost:8080/getList' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
When I try to call POST /findTracks() I've got:
Access to XMLHttpRequest at 'http://localhost:8080/findTracks' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
And I alread tried everything (as you can see in the code below).
First:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedHeaders("*").allowedMethods("*");
} //even with .allowedOrgins("http://localhost:8081");
}
Then in Controller class:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class SpotifyApiController {
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping(value = "/getList", method = RequestMethod.GET)
public List<String> getList() {
ArrayList<String> a = new ArrayList<>();
a.add("dwa");
a.add("trzy");
return a;
}
@RequestMapping(value = "/findTracks",
method = RequestMethod.POST,
consumes = "application/json",
produces = "application/json")
public List<Track> getTracksForTitles(@RequestBody TrackWrapper userTracks, TrackService tracksService, OAuth2Authentication details) {
return tracksService.generateTracksDetails(getActiveToken(details), userTracks);
}
Then in Vue:
import axios from 'axios';
const SERVER_URL = 'http://localhost:8080'
const instance = axios.create({
baseURL: SERVER_URL,
timeout: 1000
});
export default{
findTracksInSpotify:(jsonObject)=>instance.post('/findTracks',{
userTracks: jsonObject.userTracks,
headers:{
'Content-Type': 'application/json',
}
}).then(() => function(data){
return JSON.parse(data)
}),
getList:()=>instance.get('/getList',{
transformResponse:[function(data){
return JSON.parse(data)
}]
}),
}
And my Spring Security class if needed:
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.context.request.RequestContextListener;
@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
public class OAuth2Configuration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated()
.and().logout().logoutSuccessUrl("/").permitAll();
}
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
}
I even install chrome extension but it does not work either.
Can you tell me what I am doing wrong?
I think that you do not need the class
CorsConfiguration.You do not need to annotate with
CrossOrigintheSpotifyApiControllereither.The configuration of CORS ideally should be placed in the security configuration. Something like that (in
OAuth2Configuration):