'how to send jwt token correctly
In my angular application I am trying to send a jwt token as a header in order to authorize my app for requests. But I am getting an error 500 because I am sending the jwt token in a wrong format, this is how I am sending right now:
Bearer {"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ"}
What I want is the following:
Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ
I tried the following but I am getting an undefined can not read property of trim error:
token.split(" ")[1].trim()
could someone help me out and tell me what I am doing wrong? This is my interceptor where I am trying to send the header:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!request.url || (request.url.startsWith('http') && !(environment.rootUrl && request.url.startsWith(environment.rootUrl)))) {
return next.handle(request);
}
const token =
localStorage.getItem('token') ||
sessionStorage.getItem('token');
if (token) {
console.log(token)
request = request.clone({
setHeaders: {
Authorization: 'Bearer ' + token.split(" ")[1].trim()
},
});
}
return next.handle(request);
}
}
EDIT: Added the method which saves the token:
authenticateUser(login: LoginModel){
this.http = new HttpClient(this.handler)
return this.http.post(environment.rootUrl + 'api/authenticate', {
username: login.username,
password: login.password,
}).subscribe({
next: (data) => {
localStorage.setItem('token', JSON.stringify(data))
this.router.navigate(['/dashboard'])
}, error: (error) => {
this.isAuthenticated = false
}
})
console.log:
{"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxNzk0OH0.YACaabpkEWEkG6a65GspdLL9Ds50rQNBAou9f1X-mq2NMeSsNRZoabuMK3WcNAd_8t3q-yeDkNPYbMQkFD8B2g"}
}
EDIT2:
console log of data:
{id_token: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiO…nSYP5PctcyXIQ_RuoaQQ72w5bf2YO943WoRhTQTER-y0LH6iw'}
Solution 1:[1]
If the API response sends it as a JSON Object then you will need to parse the JSON using
localStorage.setItem('token', JSON.parse(data).id_token)
This will parse the incoming JSON response from the API and then get the id_token key.
However if the API response sends it as a string and NOT a JSON Object then you will get an error if you try to use JSON.parse() as it is not a valid JSON Object. Therefore you can just use
localStorage.setItem('token', data.id_token)
I dont know if your API returns a string or JSON object hence why i have provided both pieces of code.
You don't need to use token.split
Authorization: 'Bearer ' + token.split(" ")[1].trim()
You can just send the token as
Authorization: 'Bearer ' + token
Hope this solves the problem
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Smith |