Arlo Guthrie
Arlo Guthrie

Reputation: 1234

Using Amplify credentials in Angular Interceptor

We are using Amplify to authenticate to AWS Lambda. We are trying to add security to our product, so I added an interceptor to retrieve the current credentials and add them to the header of every request.

The code below correctly intercepts the request, and correctly retrieves the access token. However, because all of the moving parts are driven by asynchronous Promise / Observable, the request goes out before the header is added. What do I need to change?

I apologize for my limited experience with Promise / Observable.

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log("INTERCEPTED!!");
    this.auth.userCredentials().subscribe( result => {
        this.sessionToken = result.sessionToken;
        console.log(this.sessionToken);
        request = request.clone({
            withCredentials : true,
            setHeaders: {
                Authorization: `Bearer ${this.sessionToken}`
            }            
        });
    });
    console.log(request);
    return next.handle(request);
}

Upvotes: 1

Views: 2997

Answers (2)

Cyril Fert&#233;
Cyril Fert&#233;

Reputation: 21

import { Auth } from 'aws-amplify';
....

async getToken(){
   return (await Auth.currentSession()).getAccessToken().getJwtToken()
  }

Upvotes: 0

Arlo Guthrie
Arlo Guthrie

Reputation: 1234

This seems to work fine. There were three issues. 1) I needed to set withCredentials=false. 2) I needed to return next.handle from within my subscription. 3) The session token from user credentials is the wrong token, Cognito wants the session.idToken.jwtToken.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.auth.session().subscribe( 
        result => {
            this.sessionToken = result.idToken.jwtToken;
            request = request.clone({
                withCredentials : false,
                setHeaders: {
                    Authorization: `Bearer ${this.sessionToken}`
                }            
            });    
            return next.handle(request);
        });
    return next.handle(request);
}

Upvotes: 3

Related Questions