Filip_k_island
Filip_k_island

Reputation: 41

Headers for HttpRequest, Angular with Spring Boot

using Angular with an API built in Spring Boot. I have a problem regarding sending a request with the headers with the associated JWT. The problems seems to be that i don't send any headers at all to my API.

Angular:

greetingFunc() {

    const headers_auth = {
        'Authorization': sessionStorage.getItem("token")!
    }

    this.httpClient.get<string>(
        "http://localhost:8080/greeting", {
        'headers': headers_auth
    }).subscribe(
        data => {
            const greet = data;
            return greet; 
        }
    )
}

When inspecting page in my browser, I get the Error saying that my headers are empty: headers: HttpHeaders headers: Map(0) [[Entries]] No properties size: 0 [[Prototype]]: Map

API (Spring Boot)

System.out.println(requestTokenHeader); -->Prints null

System.out.println(request.getHeader("Authorization")); -->Prints null

When running in postman i have the following headers I have been trying the code in PostMan, where it works fine.

httpHeaders

httpOptions

Code that has been tested

intercept that is provided in app.module.ts with providers

Upvotes: 0

Views: 856

Answers (2)

TTTT
TTTT

Reputation: 1

!SOLVED In Spring Boot when overriding the addCorsMapping just add .exposedHeaders(header_name) in the registry chain.

Example:

@Override
public void addCorsMappings(final CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOrigins(clientPort)
        .allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PATCH.name(), HttpMethod.DELETE.name(), HttpMethod.HEAD.name())
        .allowedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE)
        .exposedHeaders(JwtHeader)
        .allowCredentials(true)
        .maxAge(86400);
}

Upvotes: 0

Dimitar Cetelev
Dimitar Cetelev

Reputation: 392

You need to have new instance of HttpHeaders

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    Authorization: 'my-auth-token'
  })
};

and then

this.httpClient.get<"http://localhost:8080/greeting", httpOptions)

Upvotes: 1

Related Questions