【问题标题】:How to manage cognito token lifecycle如何管理认知令牌生命周期
【发布时间】:2019-11-18 19:40:53
【问题描述】:

我有一个应用程序将使用 cognito 作为身份验证提供程序。我注意到id and access token 都在一小时后过期。这似乎不是很长时间。

我想到了两种管理令牌的方法,但不确定选择哪种/最佳做法。

在对后端的每个请求之前,我都可以检查令牌的到期时间,如果有效,请使用它,如果无效,我可以使用刷新令牌获取新令牌并使用它。

或者

我可以在每次请求时刷新令牌并为请求使用新的 id/访问令牌。

大多数人如何管理这些短暂的令牌?

【问题讨论】:

    标签: amazon-web-services aws-lambda amazon-cognito


    【解决方案1】:

    通过 cognito,您可以获得 3 种令牌,所有令牌都存储在您的存储中。 1)访问令牌。 (1小时有效) 2)ID - 令牌。 (1小时有效) 3)刷新令牌。 (有效期1个月或2个月请核实)

    // 对于 Web 应用程序

    我已将 AWS-Amplify 用于我的 Web 客户端。

    在您的登录页面中,您应该调用 Auth.currentSeesion();

    如果访问令牌和 id 令牌的生命周期(1 小时)获得 exipers,则调用此方法时,它将查找刷新令牌,然后 aws amplify 将带回访问令牌和 id 令牌并存储到存储中。

    链接:https://aws-amplify.github.io/docs/js/authentication#token-refresh

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>
    
      useEffect(() => {
        analytics.initialize();
        // Update Authorization token
        auth.currentSession()
          .then(data => {
            storage.saveDataInLocal(StorageKey.ACCESS_TOKEN, data.idToken.jwtToken);
            const { email } = data.idToken.payload;
            // checking if user was signed in by gmail
            if(props.isGoogleSigned) {
              // this code is required to auto login user if he closed the tab last time when he was logined
              props.dispatch(sendGoogleSignInRequest(email));
            }
            props.dispatch(initialCall());
          })
          .catch(() => {
            props.dispatch(initialCall());
          });
              // Validate user authentication status
        auth.currentAuthenticatedUser()
          .then(() => {
            props.dispatch(fetchAppData());
          }
          )
          .catch(() => {
            if (storage.getDataFromLocal(StorageKey.USER_INFO)) {
              props.dispatch(clearAppReducer());
              storage.clearAllLocalData();
              storage.clearAllSessionData();
              props.history.push('/login');
            }
          });
      }, []);

    【讨论】:

    • 是的。因此,在 localhost 中运行一段时间后,您会看到刷新令牌为空。但是,如果您尝试在隐身窗口中,那么您将获得刷新令牌。这一切都由放大处理。