小编Van*_*sie的帖子

使用Angular拦截Unathorized API调用

我试图拦截401403错误刷新用户令牌,但我不能让它运作良好.我所取得的就是这个拦截器:

app.config(function ($httpProvider) {

  $httpProvider.interceptors.push(function ($q, $injector) {

    return {
      // On request success
      request: function (config) {
        var deferred = $q.defer();

        if ((config.url.indexOf('API URL') !== -1)) {
          // If any API resource call, get the token firstly
          $injector.get('AuthenticationFactory').getToken().then(function (token) {
            config.headers.Authorization = token;

            deferred.resolve(config);
          });
        } else {
          deferred.resolve(config);
        }

        return deferred.promise;
      },

      response: function (response) {
        // Return the promise response.
        return response || $q.when(response);
      },

      responseError: function (response) {
        // Access token invalid …
Run Code Online (Sandbox Code Playgroud)

javascript interceptor angularjs angular-promise

21
推荐指数
1
解决办法
2233
查看次数

如果 Apollo GraphQL 令牌无效或已过期,则 NextAuth.js 注销

在尝试访问后端(Apollo GraphQL)时清除 NextAuth.js 会话的最佳方法是什么,并且由于令牌已过期或无效而返回 401?

我想到了errorLinkand signout,但据我所知signout不能在服务器端使用getServerSideProps,而只能在客户端使用。

推荐的方法是什么?有没有其他方法可以实现中间件来处理这种情况?

这将是errorLink我正在尝试实现的概念的证明,代码被困在其中,if但我无法使用,signOut()因为它仅在客户端可用

const errorLink = onError(({ graphQLErrors }) => {
   if (graphQLErrors?.[0]?.message === 'Unauthenticated.') {
    // signOut();
  }
});

function createApolloClient(session) {
  return new ApolloClient({
    cache: new InMemoryCache(),
    ssrMode: typeof window === 'undefined',
    link: from([
      errorLink,
      createUploadLink({
        uri: GRAPHQL_URI,
        credentials: 'same-origin',
        headers: { Authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '' },
      }),
    ]),
  });
}
Run Code Online (Sandbox Code Playgroud)

谢谢

apollo reactjs graphql next.js next-auth

5
推荐指数
1
解决办法
1121
查看次数