如何在 Spring Boot 中在 Spring Security 级别启用 CORS [英] How to enable CORS at Spring Security level in Spring boot

查看:25
本文介绍了如何在 Spring Boot 中在 Spring Security 级别启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用 Spring 的 Spring Boot 应用程序安全.我试过@CrossOrigin 来启用 cors,但它没有用.

I am working with a spring boot application which uses Spring Security. I have tried @CrossOrigin to enable cors but it didn't work.

如果你想找到我的错误请参考 这个

If you want to find my error refer this

Spring 博客 说当我们正在使用 spring security,我们必须在 spring 安全级别启用 cors.

Spring Blogs says that when we are working with spring security, we must enable cors at spring security level.

我的项目在下面.

谁能解释一下我应该把这些配置放在哪里以及如何找到 spring 安全级别.

Can anyone explain where should I put those configuration and how to find the spring security level.

推荐答案

这是一种让 Spring Security 4.1 支持 CROS 和 Spring BOOT 1.5 的方法

this is a way to make Spring Security 4.1 support CROS with Spring BOOT 1.5

  @Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
           .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

这篇关于如何在 Spring Boot 中在 Spring Security 级别启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆