【问题标题】:Cannot get user session from Amazon Cognito User Pools无法从 Amazon Cognito 用户池获取用户会话
【发布时间】:2018-12-22 07:12:29
【问题描述】:

我正在使用 Amazon 的 Cognito 用户池来启动 SAML SSO 身份验证。我正在使用aws-amplify,这是一个 JavaScript 库,用于使用云服务和前端的 ReactJS 进行应用程序开发。尝试使用 currentSession() 函数似乎存在一些问题。使用包的 Auth 模块的 Auth.siginIn() 函数时,我的会话似乎没有保存会话。我已经使用我在用户池中设置的当前测试用户进行了测试并成功登录。我之所以要使用Auth.currentSession() 函数是为了验证我的应用程序中每个视图的会话。下面你可以看到,在用户验证登录后,我将它们发送到我的仪表板视图,然后在组件安装后尝试验证会话,但它返回一个错误,没有找到用户。下面是我使用的代码。我查看了 aws-amplify 在其网站上的文档,但似乎无法确定问题所在。

注意:Redux 被用于存储来自 setUserData 和 setAuthToken (session 登录后回复)

Login.js

  handleSubmit = (event) => {
    event.preventDefault();
    Auth.signIn(this.state.sso, this.state.password)
    .then((res) => {
      this.props.authUser(true)
      this.props.setUserData(res.username)
      this.props.setAuthToken(res.Session)
    })
    .then(() => {
      this.props.history.push("/Dashboard")
    })
    //catches err
    .catch((e) => {
      console.log(e);
      alert(e.message)
      this.props.authUser(false)
    })
  }

一旦用户登录,用户应该被推送到仪表板。在组件生命周期中调用 componentDidMount() 后,我想检查当前会话以查看是否仍在会话中。

Dashboard.js

componentDidMount(){
    debugger;
    console.log(Auth);
    Auth.currentSession().then((res) => {
      console.log(res);
    }).catch((e) => {
      alert(e)
    })


    this.props.toggleError(false);
    this.props.toggleNotify()
  }

【问题讨论】:

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


    【解决方案1】:

    SAML 的身份验证流程与在 UserPool 中创建的用户不同。 Auth.signIn() 仅用于对已在用户池中创建的用户进行身份验证。 (AWS Amplify Documentation)

    要启动 SAML 身份验证流程,请按以下步骤操作:

    1. 将您的 SAML 提供程序设置为您的 UserPool 中的联合身份
    2. 将用户引导至您的 AWS UserPool 托管的 SAML SSO 页面。
    3. 用户将通过 SAML SSO 提供商进行身份验证,您的 UserPool 将向您的应用程序发送 JWT
    4. 使用 AWS-Amplify Auth.federatedSignIn() 方法接收 AWS IAM 凭证(将由 AWS-Amlify 管理

    本指南是第 1-3 步的绝佳资源:Amazon Cognito User Pools supports federation with SAML

    对于第 4 步:

    Auth.federatedSignIn(
        // Initiate federated sign-in with your User Pool  
        'cognito-idp.us-west-2.amazonaws.com/us-west-2_XXXXXXXXX',
        { 
            // the JWT token parsed from the response url
            token: #id_token
        },
        // (optional) a user object (a simple dictionary created from the #access_token)
        user
    ).then(() => {
        // ...
    });
    

    【讨论】:

    • 将尝试此方法并就结果提供反馈。谢谢你的详细解答!
    • 这最终奏效了。非常感谢!不过我还有一个问题。如何检查我当前的用户会话以查看它是否已过期。在 federatedSignIn 之后我也应该执行 Auth.signIn 吗?我希望能够检查加载的每个视图的会话,以验证会话是否仍然有效
    • 编辑:我发现了我的问题。您必须在 AWS Cognito 中为托管 UI 设置 oauth 配置参数;希望这可以帮助其他人解决这个问题!
    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 2016-10-23
    • 2022-11-04
    • 2017-12-03
    • 2019-09-02
    • 2017-07-06
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多