使用graphql和apollo客户端刷新用于角度的令牌

时间:2020-05-09 14:39:54

标签: angular typescript graphql apollo-client apollo-link

我正在尝试设置刷新令牌策略,以在我的第一个请求返回401时使用GraphQL和apollo客户端刷新angular 9中的JWT。

我为我创建我的apolloclient的graphql设置了一个新的angular模块。即使通过身份验证的请求,一切也都很好,但是我还需要正常的刷新令牌策略正常工作(刷新令牌周期完成后重新制作并返回原始请求)。我发现只有很少的资源可以帮助解决这个问题,而且我已经非常接近了-我唯一缺少的是从刷新令牌observable中返回observable。

以下是应该起作用的代码:

    import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';

export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {

  const authLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('auth_token')
      }
    });
    return forward(operation);
  });

  const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path }) =>
        {
         if (message.toLowerCase() === 'unauthorized') {
          authenticationService.refreshToken().subscribe(() => {
            return forward(operation);
          });
         }
        }
      );
    }
  });

  return {
    link: errorLink.concat(authLink.concat(httpLink.create({ uri: 'http://localhost:3000/graphql' }))),
    cache: new InMemoryCache(),
  };
}


@NgModule({
  exports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink, AuthenticationService]
    }
  ]
})
export class GraphqlModule { }

我知道我的请求第二次正常工作,因为如果我从authenticationService订阅中可观察到的forward(operation)中注销结果,那么我会在最初的401失败后看到结果。

 if (message.toLowerCase() === 'unauthorized') {
  authenticationService.refreshToken().subscribe(() => {
    return forward(operation).subscribe(result => {
      console.log(result);
    });
  });
 }

上面的代码向我显示了原始请求中的数据,但没有将其传递给我最初称为graphql的组件。

我离可观察性专家还很远,但是我想我需要做一些地图(flatmap,mergemap等)才能使此返回正常工作,但是我不知道。

任何帮助将不胜感激

TIA

编辑#1:这使我更加接近,因为它实际上正在AuthenticationService中订阅我的方法(我在tap()中看到结果)

    const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
    if (graphQLErrors) {
      if (graphQLErrors[0].message.toLowerCase() === 'unauthorized') {
        return authenticationService.refreshToken()
        .pipe(
          switchMap(() => forward(operation))
        );
      }
    }
  });

我现在看到抛出此错误:

core.js:6210错误TypeError:您提供了一个无效对象,该对象应用于流。您可以提供一个Observable,Promise,Array或Iterable。

编辑#2:包括onError()函数签名的屏幕截图: enter image description here

编辑#3这是最终的工作解决方案,以防其他人遇到此问题并需要其倾斜。我不喜欢必须更新我的服务方法以返回一个承诺,然后将该承诺转换为一个Observable-但是正如@AndreiGătej为我发现的那样,该Observable来自另一个命名空间。

import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
import { Observable } from 'apollo-link';


export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {

  const authLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('auth_token')
      }
    });
    return forward(operation);
  });

  const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
    if (graphQLErrors) {
      if (graphQLErrors.some(x => x.message.toLowerCase() === 'unauthorized')) {
        return promiseToObservable(authenticationService.refreshToken().toPromise()).flatMap(() => forward(operation));
      }
    }
  });

  return {
    link: errorLink.concat(authLink.concat(httpLink.create({ uri: '/graphql' }))),
    cache: new InMemoryCache(),
  };
}

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)
      );
    });


@NgModule({
  exports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink, AuthenticationService]
    }
  ]
})
export class GraphqlModule { }

2 个答案:

答案 0 :(得分:2)

我对GraphQL不太熟悉,但是我认为这应该可以工作:

if (message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
  .pipe(
    switchMap(() => forward(operation))
  );
}

此外,如果您想了解mergeMap(和concatMap)的工作方式,可以看看this answer

switchMap仅保留一个活动的内部可观察值,并且一旦传入一个外部值,将根据当前到达的外部值和所提供的函数取消订阅当前内部的可观察值并创建一个新的内部可观察值

答案 1 :(得分:1)

这是我的实现,供将来看到此内容的任何人使用

Garaphql 模块:

import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import {
  ApolloClientOptions,
  InMemoryCache,
  ApolloLink,
} from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { environment } from '../environments/environment';
import { UserService } from './shared/services/user.service';
import { onError } from '@apollo/client/link/error';
import { switchMap } from 'rxjs/operators';

const uri = environment.apiUrl;

let isRefreshToken = false;
let unHandledError = false;

export function createApollo(
  httpLink: HttpLink,
  userService: UserService
): ApolloClientOptions<any> {
  const auth = new ApolloLink((operation, forward) => {
    userService.user$.subscribe((res) => {
      setTokenInHeader(operation);
      isRefreshToken = false;
    });

    return forward(operation);
  });

  const errorHandler = onError(
    ({ forward, graphQLErrors, networkError, operation }): any => {
      if (graphQLErrors && !unHandledError) {
        if (
          graphQLErrors.some((x) =>
            x.message.toLowerCase().includes('unauthorized')
          )
        ) {
          isRefreshToken = true;

          return userService
            .refreshToken()
            .pipe(switchMap((res) => forward(operation)));
        } else {
          userService.logOut('Other Error');
        }

        unHandledError = true;
      } else {
        unHandledError = false;
      }
    }
  );

  const link = ApolloLink.from([errorHandler, auth, httpLink.create({ uri })]);

  return {
    link,
    cache: new InMemoryCache(),
    connectToDevTools: !environment.production,
  };
}

function setTokenInHeader(operation) {
  const tokenKey = isRefreshToken ? 'refreshToken' : 'token';
  const token = localStorage.getItem(tokenKey) || '';
  operation.setContext({
    headers: {
      token,
      Accept: 'charset=utf-8',
    },
  });
}

@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink, UserService],
    },
  ],
})
export class GraphQLModule {}

用户服务/身份验证服务:

import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { User, RefreshTokenGQL } from '../../../generated/graphql';
import jwt_decode from 'jwt-decode';
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, tap } from 'rxjs/operators';
import { AlertService } from './alert.service';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private userSubject: BehaviorSubject<User>;
  public user$: Observable<User>;

  constructor(
    private router: Router,
    private injector: Injector,
    private alert: AlertService
  ) {
    const token = localStorage.getItem('token');
    let user;
    if (token && token !== 'undefined') {
      try {
        user = jwt_decode(token);
      } catch (error) {
        console.log('error', error);
      }
    }
    this.userSubject = new BehaviorSubject<User>(user);
    this.user$ = this.userSubject.asObservable();
  }

  setToken(token?: string, refreshToken?: string) {
    let user;

    if (token) {
      user = jwt_decode(token);
      localStorage.setItem('token', token);
      localStorage.setItem('refreshToken', refreshToken);
    } else {
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
    }

    this.userSubject.next(user);
    return user;
  }

  logOut(msg?: string) {
    if (msg) {
      this.alert.addInfo('Logging out...', msg);
    }

    this.setToken();
    this.router.navigateByUrl('/auth/login');
  }

  getUser() {
    return this.userSubject.value;
  }

  refreshToken() {
    const refreshTokenMutation = this.injector.get<RefreshTokenGQL>(
      RefreshTokenGQL
    );

    return refreshTokenMutation.mutate().pipe(
      tap(({ data: { refreshToken: res } }) => {
        this.setToken(res.token, res.refreshToken);
      }),
      catchError((error) => {
        console.log('On Refresh Error: ', error);
        this.logOut('Session Expired, Log-in again');
        return throwError('Session Expired, Log-in again');
      })
    );
  }
}