注释 CrossOrigin 在 Spring boot 中不起作用

2023-11-29

我有一个公开一些端点的 Spring Boot 应用程序。我想从 React 应用程序向这些端点发出请求,但它一直给我带来 CORS 问题:

访问 XMLHttpRequest 'localhost:9090/helios-admin/api/dashboard/clients?page=0&size=30' 从原点'http://本地主机:3000' 已被 CORS 策略阻止: 仅支持以下协议方案的跨源请求:http、 数据、chrome、chrome 扩展、https。

所以我尝试使用@CrossOrigin我的所有方法以及控制器类的注释,但错误是相同的。
我的 React 应用程序中的 get 请求如下所示:

constructor() {
        this.url = 'localhost:9090/helios-admin/api/dashboard/clients?page=0&size=30';
    }

    getProjectStatusById(projectId) {
        Axios.get(this.url).then(res=>{
            console.log(res.data);
        })
    }

少了什么东西?

EDIT在我的 Spring Boot 应用程序中,我只有此类来配置安全性:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {



    @Autowired
    SysdataUserDetailsService sysdataUserDetailsService;



    @Autowired
    private JwtAuthEntryPoint jwtAuthEntryPoint;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(sysdataUserDetailsService)
                .passwordEncoder(encoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(PathConstants.USER_AUTH +"/**", PathConstants.HELIOS+"/dashboard/**").permitAll()
                .antMatchers(HttpMethod.GET, "/"+PathConstants.PROCESS_DEFINITION+"/**").permitAll()
                .antMatchers(HttpMethod.POST, "/"+PathConstants.PROCESS_DEFINITION+"/**").permitAll()
                .antMatchers(HttpMethod.GET, "/"+PathConstants.PROCESS_INSTANCE+"/**").permitAll()
                //.anyRequest().authenticated()
                .anyRequest().permitAll()
                .and()
                .exceptionHandling().authenticationEntryPoint(jwtAuthEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // custom jwt filter.
        http.addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

您可以通过覆盖来添加它addCorsMappings of WebMvcConfigurerAdapter,所以要么创建一个类extends WebMvcConfigurerAdapter或者在配置类中定义一个 bean,如下所示:

    @Bean
    public WebMvcConfigurer corsConfigurer () {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://domain1.com", "http://domain2.com")
                        .allowedMethods("GET", "OPTIONS")
                        .allowedHeaders("header1", "header2", "header3")
                        .exposedHeaders("header1", "header2")
                        .allowCredentials(false).maxAge(3600);
            }
        }
    }

Edit

自 5.0 起WebMvcConfigurerAdapter已被弃用,因此您可以通过实现来实现相同的效果WebMvcConfigurer接口(添加了默认方法,感谢java 8!并且可以直接实现,不需要这个适配器)

@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer {

   @Override
   public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**")
                    .allowedOrigins("http://domain1.com", "http://domain2.com")
                    .allowedMethods("GET", "OPTIONS")
                    .allowedHeaders("header1", "header2", "header3")
                    .exposedHeaders("header1", "header2")
                    .allowCredentials(false).maxAge(3600);
   }
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

注释 CrossOrigin 在 Spring boot 中不起作用 的相关文章

随机推荐