我对 SpringBoot 3 和 Angular 的 CORS 有问题

问题描述 投票:0回答:1

我已经尝试了在互联网上找到的所有内容,但似乎没有任何效果。我正在使用 Spring boot 3 和 Angular 16。这很奇怪,因为一个简单的 get 请求可以返回一个字符串。

控制台错误:从源“http://localhost:4200”访问“http://localhost:8080/api/v1/signin”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

@Configuration
public class WebConfig {
//    @Bean
//    public WebMvcConfigurer corsConfig() {
//        return new WebMvcConfigurer() {
//            @Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/api/v1/**")
//                        .allowedOrigins("http://localhost:4200")  
//                        .allowedMethods("*")
//                        .allowedHeaders("*") 
//                        .allowCredentials(true);
//            }
//        };
//    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

尝试了所有这些,就像我说的,适用于简单的获取请求。后端工作正常,我用邮递员测试了它。 前端

  private apiUrl = 'http://localhost:8080/api/v1'

  private headers
  constructor(private httpClient: HttpClient, private userService: UserService) {

    this.headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Access-Control-Allow-Origin', '*')
      
  }
  
 login(email: string, password: string): Observable<any> {
    return this.httpClient.post<LoginResponse>(
      `${this.apiUrl}/signin`,
      {
        email: email,
        password: password
      },
      { observe: 'response' }
    ).pipe(
      map((response: HttpResponse<LoginResponse>) => {
        const token = response.body?.token;
        console.log('Token:', token);
        return response;
      })
    );
  }

我三次检查了网址、数据类型,我的登录表单返回了正确的变量。这不是我第一次使用 spring 和 Angular。但我之前一直使用Spring boot 2。我不完全熟悉的唯一可能导致问题的部分是下面的这个类。

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig  {
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userService.userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder);
        return authProvider;
    }
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf
                        .disable()
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(HttpMethod.POST, "/api/v1/signup", "/api/v1/signin", "/api/v1/bizsignin","/api/v1/bizsignup").permitAll()
                        .requestMatchers(HttpMethod.GET, "/api/v1/test/**","/api/v1/greetings").permitAll()
                        .anyRequest().authenticated()
                )
                .authenticationProvider(authenticationProvider()).addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}

enter image description here enter image description here 请求成功和失败

java angular spring spring-boot cors
1个回答
0
投票

我这样做是为了开发 Spring Boot/Angular

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer{

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("http://localhost:4200")
            .allowedMethods("GET", "POST", "PUT", "DELETE");
}

}

© www.soinside.com 2019 - 2024. All rights reserved.