1

当请求因无效令牌而失败时,我正在尝试创建用于刷新 JWT 令牌的流程。我的流程如下:

  1. 使用身份验证标头发出请求
  2. 由于令牌无效而捕获失败的请求
  3. 进行 API 调用以刷新令牌并将其存储在本地存储中
  4. 在身份验证标头中设置新令牌
  5. 使用新的身份验证标头重试旧请求

但是流程的第 4 步不起作用。我能够获取新令牌,但无法在授权标头中设置它。所以旧请求是使用旧令牌而不是新令牌发送的。

如果有人能弄清楚为什么会这样。这会有很大帮助。

这是执行刷新令牌突变的函数。

public graphqlMutation(mutation:any, variable?:any){
return this.apollo.mutate({ mutation:mutation, variables:variable});
}

public getNewToken(refresh_token:any){
const token_variable = {"refresh_token": refresh_token}
this.graphqlMutation(REFRESH_TOKEN_MUTATION, token_variable)
.subscribe(
  (result:any) =>{
    const token = result.data.refreshToken.token;
    const refresh_token = result.data.refreshToken.refreshToken;
    localStorage.setItem('auth_token', token);
    localStorage.setItem('refresh_token', refresh_token);
  }
)
}

这是HttpLink终止链接

const http = this.httpLink.create({
  uri: 'http://127.0.0.1:8000/graphql/',
  withCredentials: true
});

这是设置身份验证标头的headerMiddleware

const headerMiddleware = new ApolloLink((operation, forward) => {
const token = 'JWT '+ localStorage.getItem('auth_token');
operation.setContext({
  headers: {
    'Accept': 'charset=utf-8',
    'Authorization': token ? token : ''
  }
});
return forward(operation);
});

这是捕获失败请求、获取新令牌、设置授权标头并重试旧请求的onError函数。

const graphqlError = onError(({ graphQLErrors, operation, forward }) =>{
if (graphQLErrors){
  for (let err of graphQLErrors){
    switch (err.message) {
      case 'Signature has expired':
        this.getNewToken(localStorage.getItem('refresh_token'));
        const oldHeaders = operation.getContext().headers;
        operation.setContext({
          headers: {
            ...oldHeaders,
            Authorization: 'JWT ' + localStorage.getItem('auth_token')
          }
        });
        return forward(operation);
    }
  }
}

});

这是链接

const Link = ApolloLink.from([graphqlError, headerMiddleware, http]);

这是我的package.json文件

"apollo-angular": "^1.10.0",
"apollo-angular-link-http": "^1.11.0",
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link-context": "^1.0.20",
"apollo-link-error": "^1.1.13",
"apollo-link-ws": "^1.0.20",
"graphql": "^15.3.0",
"graphql-tag": "^2.10.4",

并提前感谢您的帮助!!

4

0 回答 0