【问题标题】:How to get Cognito ID Token with in browser ?如何在浏览器中获取 Cognito ID 令牌?
【发布时间】:2018-04-02 16:50:42
【问题描述】:

我正在构建 Web 应用程序(使用 ReactJS)使用 Cognito 用户池进行用户管理,这将是使用 cloudfront、api 和 lambda 的无服务器。我正在寻求有关如何使用 Javascript 在浏览器中通过实际登录来获取 Cognito IDToken 的帮助。我只想要令牌并将其传递给 API,该 API 将从令牌中提取身份验证信息并将其用于某些特定目的。

【问题讨论】:

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


【解决方案1】:

Amazon Cognito 令牌存储在浏览器的本地存储中,但不建议直接从那里访问它们,因为它们可能会过期。

最好使用 SDK 获取它们,您可以从中获取会话,这反过来会为您刷新令牌(如果它们过期)并在会话仍然有效时为您提供有效令牌。例如:

import * as AmazonCognitoIdentity from "amazon-cognito-identity-js";

const poolData = {UserPoolId: "USER_POOL_ID", ClientId: "CLIENT_ID"};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

// React
const cognitoUser = userPool.getCurrentUser();
  if (cognitoUser != null) {
    cognitoUser.getSession((err, session) => {
      if (err) {
        console.log(err);
      } else if (!session.isValid()) {
        console.log("Invalid session.");
      } else {
        console.log("IdToken: " + session.getIdToken().getJwtToken());
      }
    });
  } else {
    console.log("User not found.");
  }

// React Native
userPool.storage.sync((error, result) => {
  if (error) {
    console.log(error);
  } else if (result === "SUCCESS") {
    const cognitoUser = userPool.getCurrentUser();
    if (cognitoUser != null) {
      cognitoUser.getSession((err, session) => {
        if (err) {
          console.log(err);
        } else if (!session.isValid()) {
          console.log("Invalid session.");
        } else {
          console.log("IdToken: " + session.getIdToken().getJwtToken());
        }
      });
    } else {
      console.log("User not found.");
    }
  } else {
    console.log("Storage sync error.");
  }
});

【讨论】:

  • 另请注意,getCurrentUser() 使用刷新令牌自动刷新令牌。
猜你喜欢
  • 2022-07-03
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 2019-05-20
  • 2020-12-13
  • 2017-10-19
相关资源
最近更新 更多