Reputation: 4908
I have a Spring API that returns an Authorization Bearer token in the header. I am able to see the token in the response header via browser tools. However, Angular logs the response as null. How can I access this header, so that I can save it in localStorage via client?
The Angular Code:
public login(): Promise<any> {
const user = {
username: 'myusername',
password: 'mypass'
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post('http://localhost:8080/login', user, httpOptions)
.toPromise()
.then(res => {
console.log(res); // Returns null
return res;
})
.catch(err => {
console.log(err);
});
}
Spring code:
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(((User) authResult.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
.compact();
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
}
Upvotes: 0
Views: 631
Reputation: 4908
Solution provided by @jonrsharpe
public login(): Observable<any> {
const user = {
username: 'username',
password: 'password'
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post('http://localhost:8080/login', user, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
}
or
public login(): Promise<any> {
const user = {
username: 'username',
password: 'password'
};
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:8080/login', user, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response'
})
.toPromise()
.then(results => {
console.log(results);
})
.catch(err => {
console.log(err);
});
}
Upvotes: 1