Error of token refreshing in apollo-angular

774 Views Asked by At

I'm building an frontend app using apollo-angular. In my app I use JWT authentication system with a short-life access token and a long-life refresh token (they are transferred in an HTTP-only cookie instead of begin stored in HTTP-header).

When I run my app, I can successfully login, but when the access token is expired, I get the following error and I can't see anything on my browser.
Error: Network error: Cannot read property 'refresh' of undefined at new ApolloError

My codes are as follows:

GraphQLModule (it is imported in AppModule) (Part is based on this question)

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { ApolloLink, Observable } from 'apollo-link';
import { onError } from 'apollo-link-error';

import { AuthService } from '../account/auth/auth.service';
import { environment } from '../../environments/environment';

const promiseToObservable = (promise: Promise<any>) =>
  new Observable((subscriber: any) => {
    promise.then(
      value => {
        if (subscriber.closed) {
          return;
        }
        subscriber.next(value);
        subscriber.complete();
      },
      err => subscriber.error(err)
    );
  });

const errorLink = onError(({ graphQLErrors, networkError }) => { // need help on linking this with graphql module
  if (graphQLErrors) {
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
  }

  if (networkError) { console.log(`[Network error]: ${networkError}`); }
});

export function createApollo(httpLink: HttpLink, authService: AuthService) {
  const basicLink = httpLink.create({
    uri: environment.apiUrl,
    withCredentials: true,
  });

  const authMiddleware = new ApolloLink((operation, forward) => {
    if (operation.operationName !== 'RefreshToken') {
      if (localStorage.getItem('loginStatus') && localStorage.getItem('loginStatus') === '1') {
        const nowtime = new Date();
        const accessExpiresIn = new Date(localStorage.getItem('accessExpiresIn'));
        const refreshExpiresIn = new Date(localStorage.getItem('refreshExpiresIn'));
        if (accessExpiresIn <= nowtime && refreshExpiresIn > nowtime) {
          return promiseToObservable(authService.refresh().toPromise()).flatMap(() => forward(operation));
        } else if (accessExpiresIn <= nowtime && refreshExpiresIn <= nowtime) {
          return promiseToObservable(authService.logout().toPromise()).flatMap(() => forward(operation));
        } else {
          return forward(operation);
        }
      } else {
        return forward(operation);
      }
    } else {
      return forward(operation);
    }
  });

  const link = ApolloLink.from([errorLink, authMiddleware, basicLink]);
  const cache = new InMemoryCache();

  return {
    link,
    cache,
  };
}

@NgModule({
  imports: [
    HttpClientModule,
    ApolloModule,
    HttpLinkModule
  ],
  exports: [
    ApolloModule,
    HttpLinkModule
  ],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink, AuthService],
    },
  ],
})
export class GraphQLModule { }

AuthService

import { map } from 'rxjs/operators';

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

const login = gql`
  mutation Login($username: String!, $password: String!) {
    getToken (
      email: $username,
      password: $password
    ) {
      payload
      refreshExpiresIn
    }
  }
`;

const refresh = gql`
  mutation RefreshToken {
    refreshToken {
      payload
      refreshExpiresIn
    }
  }
`;

const logout = gql`
  mutation Logout {
    deleteTokenCookie {
      deleted
    }
    deleteRefreshTokenCookie {
      deleted
    }
  }
`;

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  constructor(
    public router: Router,
    private apollo: Apollo,
  ) { }

  saveExpiresIn(accessExpiresIn: number, refreshExpiresIn: number) {
    const accessExpiresIn = new Date(accessExpiresIn * 1000);
    const refreshExpiresIn = new Date(refreshExpiresIn * 1000);
    localStorage.setItem('accessExpiresIn', accessExpiresIn.toString());
    localStorage.setItem('refreshExpiresIn', refreshExpiresIn.toString());
  }

  login(username: string, password: string) {
    return this.apollo.mutate({
      mutation: login,
      variables: {
        username,
        password,
      },
    }).pipe(map((result: any) => {
      this.saveExpiresIn(
        result.data.tokenAuth.payload.exp,
        result.data.tokenAuth.refreshExpiresIn
      );
      localStorage.setItem('loginStatus', String(1));

      return result;
    }));
  }

  refresh() {
    return this.apollo.mutate({
      mutation: refresh
    }).pipe(map((result: any) => {
      this.saveExpiresIn(
        result.data.refreshToken.payload.exp,
        result.data.refreshToken.refreshExpiresIn
      );

      return result;
    }));
  }

  logout() {
    return this.apollo.mutate({
      mutation: logout
    }).pipe(map((result: any) => {
      localStorage.removeItem('loginStatus');
      localStorage.removeItem('accessExpiresIn');
      localStorage.removeItem('refreshExpiresIn');

      return result;
    }));
  }
}

These codes are written to realize the following app flows:

  1. The user tries to login (send the authentication information by a graphql mutation)
  2. The backend server send the access token and refresh token to the frontend app
  3. The user tries to send a graphql query of which the result changes based on whether the user is authenticated (not-authenticated user can also see the result of the query)
  4. The frontend app checks whether the user is logged-in and whether the access token is expired
  5. If the user is logged-in and the access token is expired, the frontend app sends the refresh token with a graphql mutation to get a new access token before the original query
  6. The original query is sent after the new access token is sent back

I'm using Angular8 and apollo-angular 1.8.0.

I'm very new to Angular so I may be missing something very simple ;(
Thank you in advance!

1

There are 1 best solutions below

5
On

Not sure of the exact solution to this, but you can try to handle the error in your refresh() method with a catchError RxJS operator - maybe you need to retry or you can see more details about the error and trace it back.

import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';

//...

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  //...

  refresh() {
    return this.apollo.mutate({
      mutation: refresh
    }).pipe(
      map((result: any) => {
        if (result) {
          //...
        }
        else {
          console.warn("There was an error. See output above for details.")
        }
      }),
      catchError((error: Error) => {
        // handle the error, maybe retry
        console.log(error && error.message);
        return of(null);
      })
    );
  }

  //...

}