I’m using Angular with AWS Cognito for authentication and am trying to implement an HTTP interceptor to attach an access token to outgoing requests. My current implementation retrieves the access token, but it appears to be decoded. I need to send the encoded version of this token. Below is my code:
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Amplify } from 'aws-amplify';
import { fetchAuthSession } from 'aws-amplify/auth';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(fetchAuthSession()).pipe(
switchMap(res => {
const accessToken = res.tokens?.accessToken || '';
console.log('accessToken', accessToken);
const cloned = req.clone({
setHeaders: {
Authorization: `Bearer ${accessToken}`
}
});
return next.handle(cloned);
})
);
}
}
When I log the accessToken, it shows the decoded JWT. I need the token to be in its original encoded JWT format. How can I ensure that fetchAuthSession() provides an encoded JWT? Or is there another method I should use to fetch the encoded token?
Angular Version: Angular: 17.3.11
AWS Amplify library version: ^6.5.0
I would appreciate any help and guidance! I may be doing it completely wrong…just a bit stuck!
Many thanks!
Set up an Angular HTTP interceptor to attach JWT from AWS Amplify’s fetchAuthSession()
to requests. I thought fetchAuthSession()
would give me the encoded JWT I need for my headers. The token looks decoded in the logs. It’s showing payload info, not the compact JWT format..