【问题标题】:Get AWS Cognito user from ID Token retrieved from Token Endpoint从从令牌端点检索到的 ID 令牌获取 AWS Cognito 用户
【发布时间】:2019-07-28 15:45:35
【问题描述】:

我正在使用 Expo 和 AWS Cognito 和 AWS Amplify 构建一个 React Native 应用程序,并且我正在尝试使用 AWS 启用 Facebook、Google 等登录

我可以毫无问题地创建用户并使用 Cognito API 登录。

不过,使用第三方需要使用 Expo AuthSession 功能。

该功能本身运行良好,我可以一直从 /oauth2/token 端点检索正确的令牌。

但是,就 Amplify 而言(我知道),用户没有登录,所以当我尝试获取 Auth.currentAuthenticatedUser() 时,返回 null。

  // Open URL in a browser
  openURL = async (url) => {
    let result = await AuthSession.startAsync({ authUrl: url })
    this.getTokenbyCode(result.params.code)
  };

getTokenbyCode = async (code) => {
    const details = {
      grant_type: 'authorization_code',
      code,
      client_id: '10eavoe3ufj2d70m5m3m2hl4pl',
      redirect_uri: AuthSession.getRedirectUrl()
    }
    const formBody = Object.keys(details)
      .map(
        key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`
      )
      .join("&");

    await fetch(
      'https://presentor.auth.us-west-2.amazoncognito.com/oauth2/token',
      {
        method: "POST",
        headers: {
          'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body: formBody
      }
    )
      .then(async (res) => {
        console.log('res: ', res);
        let resJSON = await res.json();
        let idToken = await resJSON.id_token;
        let decodedToken = jwt(idToken);
        let userData = {
            Username : decodedToken["cognito:username"],
            Pool : Auth.userPool
        }
      })
      .catch(error => {
        console.log('error: ', error);
      });
  }

当我解码令牌时,我看到了预期的负载,但是如果我想使用 API 在令牌过期时刷新它,我必须手动解决(检查过期并检索一个新的令牌过期)。

我错过了一些基本的东西吗?

【问题讨论】:

    标签: react-native amazon-cognito aws-amplify


    【解决方案1】:

    好的,我想通了。不确定这是否是正确的道路,但它很干净而且很有效,所以我很擅长。

    1. 使用 amazon-cognito-identity-js 创建 CognitoIdToken、CognitoAccessToken 和 CognitoRefreshToken 对象
    2. 从这些令牌创建用户会话
    3. 从该用户会话创建用户

      await fetch(
        'TOKEN ENDPOINT',
        {
          method: "POST",
          headers: {
            'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
          body: formBody
        }
      )
        .then(async (res) => {
          const IdToken = new CognitoIdToken({ IdToken: tokenRequestJson.id_token });
          const AccessToken = new CognitoAccessToken({ AccessToken: tokenRequestJson.access_token });
          const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokenRequestJson.refresh_token })
          try {
            let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });
            console.log('userSession: ', userSession);
            const userData = {
              Username: userSession.idToken.payload.email,
              Pool: userPool
            };
            console.log('userData: ', userData);
            cognitoUser = new CognitoUser(userData);
            cognitoUser.setSignInUserSession(userSession);
            cognitoUser.getSession((err, session) => { // You must run this to verify that session (internally)
              if (session.isValid()) {
                console.log('session is valid');
                this.setState({user: cognitoUser})
                this.props.navigation.navigate('AuthLoading')
              } else {
                console.log('session is not valid: ', session);
              }
            })
          }
          catch (FBSignInError) {
            console.log('FBSignInError: ', FBSignInError)
          }
        })
        .catch(fetchError => console.log('fetchError: ', fetchError))
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 2019-06-22
      • 2019-03-23
      • 2019-04-23
      • 2020-11-20
      • 2019-05-20
      • 2019-02-28
      • 2015-08-26
      相关资源
      最近更新 更多