Springboot java @CrossOrigin 不起作用,因为它应该起作用,当这个注释存在时为啥我必须做额外的配置?

Posted

技术标签:

【中文标题】Springboot java @CrossOrigin 不起作用,因为它应该起作用,当这个注释存在时为啥我必须做额外的配置?【英文标题】:Springboot java @CrossOrigin doesn't work as it should work, why must I do extra configurations when this annotation Is present?Springboot java @CrossOrigin 不起作用,因为它应该起作用,当这个注释存在时为什么我必须做额外的配置? 【发布时间】:2019-01-26 10:47:05 【问题描述】:
@CrossOrigin(origins="http://localhost:3000") 
@RequestMapping(value="", method = RequestMethod.GET)
public ResponseEntity<List<Client>> getAllClients(/*@RequestParam("page") int page, @RequestParam("size") int size*/) 

    List<Client> clientList = services.getClientsList(/*page,size*/);
    if(clientList != null) 
        return new ResponseEntity<>(clientList, HttpStatus.OK);
    else
        return  new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    

如果 spring boot 提供了 @CrossOrigin,为什么它不能正常工作?

谢谢,

提前...

【问题讨论】:

是的,它在 3000 上运行并且它没有接收数据返回......相反,我得到了选项 401......是的,这意味着我试图在未经授权的情况下访问受保护的资源......但是为什么当@CrossOrigin 旨在解决这个问题时是这样吗?我正在使用 5.0.8 版本 是的,我的 POM 文件中有 spring 安全依赖项 对不起,如果没有配置,我的意思是删除 spring 安全依赖 当我删除这种依赖时,我将无法对密码进行哈希处理......我该如何解决......? 我理解男人......对不起......;生产中会出现 401 吗? 【参考方案1】:

所以 Spring 安全性和 @CrossOrigin 注解不会相互交流。

您还需要为 Spring Security 配置 CORS。

您可以在official doc 中找到:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
            .authorizeRequests()
            .anyRequest().fullyAuthenticated().and()
            .httpBasic()
            .and()
            .csrf().disable()
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    

    @Bean
    CorsConfigurationSource corsConfigurationSource() 
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    

否则您可以尝试使用 globla 配置:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer 

    @Override
    public void addCorsMappings(CorsRegistry registry) 
        registry.addMapping("/**");
    

这适用于所有来源,对开发者有好处

【讨论】:

【参考方案2】:

我在 chrome 上禁用了 Web 安全...它给了我 200 个状态码...请参阅 ***.com/questions/35588699/

【讨论】:

以上是关于Springboot java @CrossOrigin 不起作用,因为它应该起作用,当这个注释存在时为啥我必须做额外的配置?的主要内容,如果未能解决你的问题,请参考以下文章

java~springboot~目录索引

Java开发SpringBoot开发(狂神说Java)

springboot的java打印票据

SpringBoot.12.SpringBoot中的拦截器

java [kafka] kafka with springboot #kafka #springboot

SpringBoot.12.SpringBoot中的拦截器