1

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>
4
  • 1
    With web.ignoring().antMatchers("/**"); you disabled Spring Security at all. So your problem is your own filter: AuthFilter it redirects the preflight request. Your filter shouldn' redirect the preflight request. Commented Jul 29, 2021 at 9:50
  • I agree with the above, you have disabled web security, which means you have disabled the CORS filter. So you can configure it as much as you want, it wont work. Commented Jul 29, 2021 at 10:01
  • @Toerktumlare could you provide me the change I need to make in AuthFilter class Commented Jul 29, 2021 at 11:30
  • 1
    Remove the web.ignoring and stop disabling the use of web security (CORS is web security) Commented Jul 29, 2021 at 11:52

2 Answers 2

-1

add @CrossOrigin("http://localhost:4200") on main method, if you want it for specific controller then add annotation on controller.

Sign up to request clarification or add additional context in comments.

2 Comments

I added it on the controller class already @CrossOrigin(origins ="localhost:4200")
none of this works in 2022
-1

Add a @CrossOrigin annotation to any of the following:

  • Controller Method level - This restricts / enables cross-origin resource sharing only for this specific method.

    @CrossOrigin(origins = "http://localhost:4200")

  • Global CORS

public WebMvcConfigurer corsConfigurer() {
  return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080");
      }
  };
}

Note: Its important to share the complete URL (with http://) in origin

For more refer: https://spring.io/guides/gs/rest-service-cors/

1 Comment

Already added this in the controller method level @CrossOrigin(origins = "localhost:4200") but still i get the preflight request error. I don't want to enable CORS globally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.