如何使用 AWS coginto auth sdk 刷新令牌

时间:2021-03-17 21:56:20

标签: reactjs amazon-cognito access-token

我正在研究令牌过期后刷新令牌的功能。我使用 amazon-cognito-auth-js 进行授权并检查 here 作为示例,我实现了以下方法来刷新令牌。但是它不起作用。 下面是我的代码,会话没有按照我的预期刷新。没有 Synax 错误,只是 auth 令牌仍然过期。 顺便说一下,我用的是 react。

import { CognitoAuth } from 'amazon-cognito-auth-js';
class Main extends Component {
   constructor() {
        this.state = {
            auth: ""
       }
   }
   componentDidMount() {
        //some logic to get the auth once user login success
        //here is the logic  to update the correct auth into the state
        this.setState({
            auth: auth
        })
    }
 //here is the method that check the token expire or not, if expire, refresh the token and update the state
   checkTokenExpiration (){
        let auth = this.state.auth;
        let user = auth.getCachedSession();
 //ideally, there shall have the logic to check the session is expired or not
// anyidea how to write it?
        auth.refreshSession(user.getRefreshToken().getToken());
        this.setState({
            auth:auth
        })
}

}

1 个答案:

答案 0 :(得分:0)

我自己结束了这个问题。 我的解决方案是在前端设置一个计时器,一旦计时器超过 1 小时(例如)。只需让用户注销即可。 Here 是您不应在 SPA 中刷新令牌的原因。 而here是处理refresh_token expire的解决方案