Read custom HTTP headers sent from Java Spring Boot using Angular, got null

Discussão em 'Angular' iniciado por dogteeth, Dezembro 24, 2024.

  1. dogteeth

    dogteeth Guest

    I use Angular to read http header from Java Spring Boot, It works fine in Postman. I can read all the headers. But when I use Angular, I got status 200, but null for headers. Please help. Where did i go wrong?

    this is my java spring api

    my rest api:

    @GetMapping("/welcome")
    public ResponseEntity<String> welcome(){
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization","test token");
    return ResponseEntity
    .status(HttpStatus.OK)
    .headers(headers)
    .build();
    }


    my spring security setup for all headers:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
    .cors(cors -> cors.configurationSource(new CorsConfigurationSource() {
    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {

    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowCredentials(true);
    config.setAllowedHeaders(Collections.singletonList("*"));
    config.setMaxAge(3600L);
    return config;
    }
    }))
    .csrf(csrf -> csrf.disable())
    .authorizeHttpRequests(auth -> auth
    .requestMatchers("/welcome","/","/login","/register").permitAll()
    // .requestMatchers("/products").authenticated()
    .anyRequest().authenticated()
    )
    .formLogin(formLogin -> formLogin.disable())
    .httpBasic(withDefaults());

    return http.build();
    }


    this is my angular http request

    my http service setup:

    getWelcome$(): Observable<HttpResponse<any>> {
    return this.httpClient.get<any>(this.url_welcome, {
    observe: 'response',
    withCredentials: true,
    });
    }


    my component function:

    onGetWelcome() {
    this.httpService.getWelcome$().subscribe({
    next: (res: HttpResponse<any>) => {
    this.authHeader = res.headers.get('Authorization') as string;
    console.log(res.status);
    console.log(this.authHeader);
    },
    error: (error) => console.log(error),
    complete: () => console.log('completed.'),
    });
    }


    I've changed HttpResponse < any > to HttpReponse < string > , doesn't work. When I tried to read the headers from other website like {JSON} Placeholder, my angular can read certain header like "Content-Type". So I guess it's my Java ResponseEntity went wrong. I changed Java ResponseEntity, headers.set, headers.add, different approach that I can get from web. No luck.

    Any idea?

    Continue reading...

Compartilhe esta Página