当前位置: 首页 > 知识库问答 >
问题:

在Spring Boot应用程序中配置cors。Bean CorsConfigurationSource不工作

狄峻熙
2023-03-14

我使用spring boot web Security。

@EnableWebSecurity
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

    @Value(value = "${auth0.apiAudience}")
    private String apiAudience;
    @Value(value = "${auth0.issuer}")
    private String issuer;


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        configuration.addAllowedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JwtWebSecurityConfigurer
                .forRS256(apiAudience, issuer)
                .configure(http)
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/api/public").permitAll()
                .antMatchers(HttpMethod.GET, "/api/private").authenticated()
                .antMatchers(HttpMethod.GET, "/api/private-scoped").hasAnyAuthority("read:posts");
    }
}

这个bean应该添加这个cors头,但它没有。也许你知道这样做的更好的主意吗?WebSecurityConfigurerAdapter和WebMVCConfigurerAdapter有什么区别?

共有1个答案

诸俊才
2023-03-14

根据这一点,您还应该在configure()方法中添加.cors().and()

还有其他可能的解决方案,例如,通过设置特定于每个endpoint的CORS-configuration(CORS-configuration)。

不过,如果您想为整个应用程序启用CORS,第一种方式要漂亮得多。

 类似资料:
  • 问题内容: 我将Spring Boot与Spring Security和Cors支持一起使用。 如果我执行以下代码 结果我得到了 如果我使用错误的凭证进行测试,例如 我得到的不是401(这是Spring安全中错误身份验证的标准代码) 带有以下浏览器通知: 获取http:// localhost:5000 / api / token XMLHttpRequest无法加载http:// localho

  • 我使用带有Spring Security和Cors支持的Spring Boot。 带有以下浏览器通知: 获取http://localhost:5000/api/token XMLHttpRequest无法加载http://localhost:5000。请求的资源上没有“access-control-allow-origin”标头。因此,不允许访问源“http://localhost:3000”。响

  • 我已经为Postgresql启用了复制,并且正在使用PGPool进行负载平衡。 我在使用HikariCP甚至Apache DBCP连接到Postgres时遇到了问题。 在SpringBoot应用程序中有没有使用PGPool的方法? 请查找堆栈跟踪: 2018-08-10 10:20:19.124信息37879----[main]com.zaxxer.hikari.hikaridatasource:

  • 我在WebSphere控制台上部署了WAR文件,并将其映射到数据源。我能够测试我用PostgreSQL服务器详细信息配置的数据源。但是我的应用程序没有连接到服务器。我是新来的WebSphere,谁能帮我配置基于下面context.xml文件的数据源。我的应用程序在tomcat中工作得很好,但在WebSphere中却不行。 我认为我在数据源配置中做错了什么。

  • 我正在寻找涉及一个使用kafka消费者和生产者的spring应用程序(别人的设计)的帮助。该设计允许config.properties文件包含如下条目: Kafka地址=10.10.10.12:9093,10.10.10.11:9093,10.10.10.10:9093 这样的配置被某种像这样的Spring豆代码所拾取...... Java代码... 它出现在我在调试器中看到的属性对象中。 “Ka

  • 我试图在SpringMVC中运行SpringBoot应用程序,在SpringMVCPOM中添加SpringBoot应用程序依赖项,并扫描SpringBoot包,但我面临以下问题