Springboot basically handles cors configuration if you provide it like that but in your case it might be because the spring security is not adding the CORS headers like Access-Control-Allow-Origin
in your response header.When you make an ajax request a pre-flight check request is initially made to the server and the server responds with a set of headers, which is used to determine whether the server supports the cors request.
When you add the cors configuration the pre-flight check from the browser will now be handled by Spring MVC, but we need to tell Spring Security that it is allowed to let it through, you could do it by adding a cors configuration bean like you provided but you need to set http.cors
like :
http.cors().and().authorizeRequests()
.anyRequest().authenticated();
so that the pre-flight requests are authenticated.
If issues still persists (By adding a custom filter) :
So,try adding a filter to set the CORS headers properly like(do set the headers properly as you require to be returned from endpoint) :
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request= (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", true);
response.setHeader("Access-Control-Max-Age", 180);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
When you set the http.cors()
in configuration , it will exclude the pre-flight check from the spring security.