Reputation: 41
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
I have been trying the code in PostMan, where it works fine.
Upvotes: 0
Views: 856
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
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