Yêu cầu thg 2 7, 2023 8:18 SA 132 0 2
  • 132 0 2
0

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

Chia sẻ
  • 132 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 thg 2 7, 2023 2:00 CH
Đã đượ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ẻ
thg 2 8, 2023 1:14 SA
Đã trả lời thg 2 9, 2023 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

Chia sẻ
thg 2 10, 2023 6:10 SA

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

Avatar lethaianhle @lethaianhle
thg 2 10, 2023 8:33 SA

@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í