I am working on a project with FE as react and BE as Springboot. I am trying to add FE to the application. After registration, I have tried to login to the application. After successful login, we get JWT Token. For that we need to send username, password and grant type in body and Basic authentication details in header. The is
var postData = { username: a, password: b, grant_type:'c' };
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json" ,
"Authorization":"Basic" " " base64.encode("U" ":" "p")
}
};
axios.post('http://localhost:9003/login/token', postData,axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
When I run this program, I got the error,
Access to XMLHttpRequest at 'http://localhost:9003/login/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And My Spring boot Code is
@Override
@CrossOrigin(origins = "*", allowedHeaders = "*") public void
configure(HttpSecurity http) throws Exception {
http.cors().and().exceptionHandling() .authenticationEntryPoint( (request,
response, authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and().authorizeRequests().antMatchers("/*").authenticated().and().httpBasic();
http.exceptionHandling().authenticationEntryPoint(new
CustomAuthenticationEntryPoint());
}
@Override
@CrossOrigin(origins = "*",allowedHeaders="*")
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.pathMapping("/oauth/token", "/login/token").tokenStore(tokenStore())
.tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
Anybody know how to solve this?
CodePudding user response:
As per MDN docs, the pre-flight response headers for a credentialed request should include a specific set of Access-Control-Allow-Origin
and not a wild-card *
.The cors config for the service can be setup by extending the WebSecurityConfigurerAdapter
.
We faced a similar challenge with our spring-boot project and the following configuration helped overcome the cors failure
@EnableWebSecurity
public class DefaultAuthConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors(cors -> {
CorsConfigurationSource cs = resources -> {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000","http://localhost:3001"));
corsConfiguration.setAllowedMethods(List.of("POST", "GET", "PUT", "DELETE", "OPTIONS"));
corsConfiguration.setAllowedHeaders(List.of("Authorization",
"Content-Type",
"X-Requested-With",
"Accept",
"X-XSRF-TOKEN"));
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
};
cors.configurationSource(cs);
});
}
}
CodePudding user response:
This class below to config CORS policy it worked for me.And i think your poblem is @CrossOrigin should be located in controller class.
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
If you want more config follow this link https://spring.io/guides/gs/rest-service-cors/