【问题标题】:Calling API with refreshed JWT token使用刷新的 JWT 令牌调用 API
【发布时间】:2018-09-13 07:04:17
【问题描述】:

目前为我的反应应用程序使用 AWS Cognito 开发工具包。 目前,在调用 API 时,我使用 ComponentWillMount 运行会话检查

componentWillMount() {
  if (!this.props.authenticated) {
    this.props.history.push('/auth/login');
  } else {
    getUserFromLocalStorage()
      .then(data => {
        console.log('getUserFromLocalStorage');
        this.props.setUserToReduxState(data);

        console.log(
          'user sucess retrieved from local storage and usersettoreduxstate: ',
          data
        )
        .then(console.log('after local test'))
      })

      .catch(() => {
        logoutUserFromReduxState();
      });
  }
}

在 componentDidMount 中,我使用本地存储中的 JWT 令牌调用 API

componentDidMount() {
// calls API with localStage.jwtToken
this.loadData();
}

这在大多数情况下都有效,但是当令牌过期时,JWT 会被刷新,这一切都会得到处理,但是当最初调用 API 时,它会使用旧的 JWT 调用。我可以看到新的 JWT 在 redux 中被刷新,但它在调用 API 之前被刷新。

是否有任何建议可以确保在进行每次 API 调用之前,令牌在用于 API 调用之前在 redux 中刷新和更新?

【问题讨论】:

    标签: reactjs redux react-redux jwt cognito


    【解决方案1】:

    这可能是由于 javascript 的异步特性造成的。只需确保 this.lodaData() 等待刷新令牌即可。

    例如,componentWillMount 运行身份验证部分,componentDidMount 在进行API 调用之前不会等待身份验证函数完成运行。

    现在这无法通过将身份验证部分和 API 分开来完成,但您可以将它们全部放在同一事件中,或者全部放在 componentWillMount 或 componentDidMount 中,并确保 API 调用在所有身份验证后被调用。如下所示

    refreshToken() {
        return new Promise((resolve, reject) => {
            //refresh token
            resolve()
        })
    }
    
    componentDidMount(){
        this.refreshToken().then(() => {
            //API call
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2019-10-10
      • 2016-03-05
      相关资源
      最近更新 更多