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

查看:48
本文介绍了注释 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 在'本地主机:9090/helios-admin/api/dashboard/clients?page=0&size=30'来自 origin '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 注释,但错误是相同的.
我的 React 应用程序中的 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 来添加它,因此要么创建一个 extends 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天全站免登陆