I am trying to enable the CORS support in Spring Boot app but I am not getting successful. I looked into a lot of solutions but none seems to be working for me.
When I try to make a call from the Angular app to Java backend I see the error in chrome:
Access to XMLHttpRequest at 'http://localhost:8080/..' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I have enabled CORS in controller method level by adding the following annotation but still I get the preflight request error.
@CrossOrigin(origins = "http://localhost:4200")
My Spring Security configuration:
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
}
My custom filter:
@Configuration
public class AuthFilter implements Filter {
@Autowired
private Environment env;
private static final ApplicationLogger logger = ApplicationLogger.getInstance();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.debug("Initializing authentication filter.");
}
public boolean checkHeader(HttpServletRequest httpRequest) {
boolean flag = false;
String applicationName = httpRequest.getHeader("bar");
if (applicationName != null && applicationName.equalsIgnoreCase("foo")) {
flag = true;
}
return flag;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// HttpSession httpSession = httpRequest.getSession();
List<String> excludedUrls = null;
String excludePattern = env.getProperty("excludedUrls");
excludedUrls = Arrays.asList(excludePattern.split(","));
String path = ((HttpServletRequest) request).getServletPath();
String loginPathURL = env.getProperty("loginPathURL");
if (excludedUrls.contains(path)
|| path.contains("/file/..")
|| path.contains("/file/...")
|| path.contains("/file/....")) {
chain.doFilter(request, response);
} else if (checkHeader(httpRequest)) {
// Authenticate the request through LDAP
logger.info("Authenticating the request ...");
chain.doFilter(request, response);
} else {
logger.debug("User is not authenticated");
httpResponse.sendRedirect(loginPathURL);
}
/*
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession httpSession = httpRequest.getSession();
List<String> excludedUrls = null;
String excludePattern = env.getProperty("excludedUrls");
excludedUrls = Arrays.asList(excludePattern.split(","));
String path = ((HttpServletRequest) request).getServletPath();
if (excludedUrls.contains(path)) {
// Authenticate the request through LDAP
logger.info("Authenticating the request ...");
chain.doFilter(request, response);
}
else if(checkHeader(httpRequest)) {
else if (httpSession != null && httpSession.getAttribute(WorkpermitConstants.CLIENT_AUTH_TOKEN_KEY) != null) {
List<Map<String,Object>> res = (List<Map<String,Object>>) jdbcTemplate.queryForList("some select query") ;
if(!AppUtil.isObjectEmpty(res.size())) {
for (Map<String, Object> row : res) {
//currentUserEmail
//empType
//userId
//username
}
}
chain.doFilter(request, response);
} else {
logger.debug("User is not authenticated.");
HttpServletResponse httpResponse = (HttpServletResponse) response;
//httpResponse.sendRedirect(httpRequest.getContextPath() + "/");
httpResponse.sendRedirect("http://..");
}
*/
// comment below code
// chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
I added the following code in my class after looking into few solutions but it did not work for me either.
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
// NOTE: setAllowCredentials(true) is important,
// otherwise, the value of the 'Access-Control-Allow-Origin' header in the response
// must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// NOTE: setAllowedHeaders is important!
// Without it, OPTIONS preflight request will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Accept",
"Cache-Control",
"Content-Type",
"Origin",
"ajax",
"x-csrf-token",
"x-requested-with"
));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Spring Boot Version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
web.ignoring().antMatchers("/**");you disabled Spring Security at all. So your problem is your own filter:AuthFilterit redirects the preflight request. Your filter shouldn' redirect the preflight request.web.ignoringand stop disabling the use of web security (CORS is web security)