Angular Apollo中间件未刷新身份验证令牌

时间:2020-10-03 23:28:59

标签: angular graphql apollo

我正在尝试使用Apollo Angular在请求标头中设置身份验证令牌。

当我第一次加载应用程序时,我的中间件(https://www.apollographql.com/docs/angular/recipes/authentication/#header)会从本地存储初始化令牌,但它不会在我发送的每个请求中都验证令牌。

我发现的唯一解决方法是在登录时强制刷新页面。

我希望中间件每次发送请求时都验证本地存储令牌。

如果有人对此有解决方案或其他方法可以实现,我将不胜感激。

谢谢!

graphql.module.ts

export function provideApollo(httpLink: HttpLink) {
  const basic = setContext((operation, context) => ({
    headers: {
      Accept: "charset=utf-8",
    },
  }));

  // Get the authentication token from local storage if it exists
  const token = localStorage.getItem(TOKEN_KEY);
  const auth = setContext((operation, context) => ({
    headers:
      token !== null
        ? {
            Authorization: `Bearer ${token}`,
          }
        : {},
  }));

  const link = ApolloLink.from([basic, auth, httpLink.create({ uri })]);
  const cache = new InMemoryCache();

  return {
    link,
    cache,
  };
}

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

0 个答案:

没有答案