从从令牌端点检索的ID令牌获取AWS Cognito用户

时间:2019-03-06 21:12:25

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

我正在使用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刷新令牌(如果令牌过期),我必须手动解决(检查过期并检索新的令牌)令牌(如果已过期)。

我缺少基本的东西吗?

1 个答案:

答案 0 :(得分:0)

好,我知道了。不确定这是否是正确的路径,但是它很干净而且可以工作,所以我很满意。

  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))