简体   繁体   English

启用 CORS 支持 Spring Boot

[英]Enable CORS support Spring Boot

I am trying to enable the CORS support in Spring Boot app but I am not getting successful.我正在尝试在 Spring Boot 应用程序中启用 CORS 支持,但没有成功。 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:当我尝试从 Angular 应用程序调用 Java 后端时,我在 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.从源 'http://localhost:4200' 访问 XMLHttpRequest at 'http://localhost:8080/..' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:不允许重定向对于预检请求。

I have enabled CORS in controller method level by adding the following annotation but still I get the preflight request error.我通过添加以下注释在控制器方法级别启用了 CORS,但仍然出现预检请求错误。

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

My Spring Security configuration:我的 Spring Security 配置:

@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>

在 main 方法上添加@CrossOrigin("http://localhost:4200") ,如果您希望它用于特定控制器,则在控制器上添加注释。

Add a @CrossOrigin annotation to any of the following:@CrossOrigin注释添加到以下任何一项:

  • Controller Method level - This restricts / enables cross-origin resource sharing only for this specific method.控制器方法级别 - 这仅针对此特定方法限制/启用跨源资源共享。

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

  • Global CORS全球 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注意:在源中共享完整的 URL(带有 http://)很重要

For more refer: https://spring.io/guides/gs/rest-service-cors/更多请参考: https : //spring.io/guides/gs/rest-service-cors/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM