I am facing issues with the CORS support for Spring Rest Implementation. Strange thing here is, I can login successfully with Rest API but after login, getting exception as-
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 401.
Code Snippet I am using is as following -
Configuration Class -
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CorsInterceptor());
}
};
}
CorsInterceptor Class -
public class CorsInterceptor extends HandlerInterceptorAdapter {
public static final String CREDENTIALS_NAME = "Access-Control-Allow-Credentials";
public static final String ORIGIN_NAME = "Access-Control-Allow-Origin";
public static final String METHODS_NAME = "Access-Control-Allow-Methods";
public static final String HEADERS_NAME = "Access-Control-Allow-Headers";
public static final String MAX_AGE_NAME = "Access-Control-Max-Age";
static final String ORIGIN = "Origin";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String origin = request.getHeader(ORIGIN);
response.addHeader(ORIGIN_NAME, origin);
response.setHeader(CREDENTIALS_NAME, "true");
response.setHeader(METHODS_NAME, "GET, POST, PUT, OPTIONS, DELETE");
response.setHeader(HEADERS_NAME,
"Authorization, Accept-Encoding,Cache-Control, Connection, Content-Length, Cookie,Host, If-Modified-Since, Pragma, User-Agent,Content-Type");
response.setHeader(MAX_AGE_NAME, "3600");
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
return true;
}
Here, I am able to login successful, (first preflight request then actual request, both are working fine). After this I am calling POST request (First preflight request is getting called), but its giving me exceptions as -
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 401.
I have tried using CorsConfiguration and also CorsRegistry as -
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("")
.allowCredentials(true).maxAge(3600);
But no luck.
Let me know If I am missing something here.
Thanks.