Yêu cầu Feb 7th, 2023 8:18 a.m. 133 0 2
  • 133 0 2
0

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

Chia sẻ
  • 133 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 CÂU TRẢ LỜI


Đã trả lời Feb 7th, 2023 2:00 p.m.
Đã được chấp nhận
+4

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;
    }
Chia sẻ
Feb 8th, 2023 1:14 a.m.
Đã trả lời Feb 9th, 2023 8:13 a.m.
+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

Chia sẻ
Feb 10th, 2023 6:10 a.m.

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

Avatar lethaianhle @lethaianhle
Feb 10th, 2023 8:33 a.m.

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

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí