Springboot java @CrossOrigin无法正常运行,为什么应该运行额外的配置?

时间:2018-08-20 10:10:15

标签: java spring-boot spring-security cors

@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 ,为什么它不能正常工作?

谢谢

提前...

2 个答案:

答案 0 :(得分:0)

因此,Spring安全性和@CrossOrigin注释不会互相交谈。

您还需要为弹簧安全性配置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("/**");
    }
}

这是所有来源的东西,对开发有好处

答案 1 :(得分:-1)

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