When working on my angular application, I encountered an issue while trying to send a jwt token as a header for request authorization. The error 500 was triggered due to the jwt token being sent in an incorrect format. Here is how I am currently sending it:
Bearer {"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ"}
What I actually need is:
Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ
I attempted the following, but encountered an "undefined can not read property of trim" error:
token.split(" ")[1].trim()
I would appreciate some guidance on where I may be going wrong. Below is my interceptor code that handles sending 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'}