Asked thg 2 7, 8:18 SA 108 0 2
  • 108 0 2
0

Làm sao Enabel CROS cho tất cả request vào trong spring boot

Share
  • 108 0 2

Chào mọi người,

Mình bị lỗi khi call api từ reactjs sang Java Spring Boot thì bị lỗi CROS, mn có cách nào mở cho tất cả request không ạ?

Mình cảm ơn!

2 ANSWERS


Answered thg 2 7, 2:00 CH
Accepted
+3

Bác có thể tham khảo phần config CorsConfiguration này ạ

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
        AuthenticationManager authenticationManager = authenticationManagerBuilder.build();

        http.cors().configurationSource(request -> corsConfiguration())
                .and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .antMatchers("/api/users/**").authenticated()
                .and().authenticationManager(authenticationManager)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        return http.build();
    }

    CorsConfiguration corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.applyPermitDefaultValues();
        corsConfiguration.addAllowedMethod(HttpMethod.PATCH);
        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        return corsConfiguration;
    }
Share
thg 2 8, 1:14 SA
Answered thg 2 9, 8:13 SA
+1

@CrossOrigin bạn có thể thử dùng annotation này :l tuy nhiên theo lỗi bảo mật của cwe thì ko nên cấu hình là * nhé. Hoặc có thể disable trong security config

Share
thg 2 10, 6:10 SA

Bạn disable trong security config như nào ạ

0
| Reply
Share
Avatar lethaianhle @lethaianhle
thg 2 10, 8:33 SA

@huytvomi như code bạn ở trên ý ạ ✌️

0
| Reply
Share
Viblo
Let's register a Viblo Account to get more interesting posts.