注释CrossOrigin在Spring Boot中不起作用 [英] Annotation CrossOrigin not working in Spring boot

查看:1477
本文介绍了注释CrossOrigin在Spring Boot中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring Boot application that exposes some endpoints. From a React app I want to make requests to these endpoints, but it keeps giving me CORS problem:

在以下位置访问XMLHttpRequest 'localhost:9090/helios-admin/api/dashboard/clients?page = 0& size = 30' 来自来源" http://localhost:3000 "已被CORS政策阻止: 跨源请求仅支持以下协议方案:http, 数据,chrome,chrome扩展名,https.

access to XMLHttpRequest at 'localhost:9090/helios-admin/api/dashboard/clients?page=0&size=30' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

所以我尝试对所有方法以及Controller类使用@CrossOrigin批注,但是错误是相同的.
我的应用程序中的get请求看起来像这样:

So I've tried using @CrossOrigin annotation for all my methods and also for the Controller class, but the error is the same.
The get request in my react app looks like this:

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);
        })
    }

缺少什么?

编辑 在我的spring boot应用程序中,我只有此类可配置安全性:

EDIT In my spring boot app I have only this class to configure security:

@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);
    }
}

推荐答案

您可以通过覆盖WebMvcConfigurerAdapteraddCorsMappings进行添加,因此可以创建扩展 WebMvcConfigurerAdapter的类或定义这样的配置类中的一个bean:

You can add it by overriding addCorsMappings of WebMvcConfigurerAdapter, so either create a class that extends WebMvcConfigurerAdapter or define a bean in your configuration class like this:

    @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);
            }
        }
    }


修改

从5.0版本开始不推荐使用WebMvcConfigurerAdapter,因此您可以通过实现WebMvcConfigurer接口来实现同一目的(添加了默认方法,感谢Java 8!可以直接实现而不需要此适配器)

As of 5.0 WebMvcConfigurerAdapter is deprecated and hence you could acheive the same thing by implementing WebMvcConfigurer interface (added default methods, thanks java 8 ! and can be implemented directly without the need for this adapter)

@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);
   }
 }

这篇关于注释CrossOrigin在Spring Boot中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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