gpt4 book ai didi

reactjs - Reactjs 中的 AWS Cognito 身份验证

转载 作者:行者123 更新时间:2023-12-04 12:35:09 30 4
gpt4 key购买 nike

我已经使用 Firebase 和 React 构建了应用程序,并且该过程非常无缝。
最近我被要求使用 AWS Cognito,由于文档不清楚,设置起来似乎有点麻烦。
首先,如何使用 Cognito 进行用户身份验证?我设置了一个用户池,使用以下应用程序客户端设置:
enter image description here
现在,我将授权方添加到我的 API 中,如下所示:
enter image description here
现在我的问题是,如何在我的前端使用它来登录用户并进行经过身份验证的 API 调用?
似乎有两种不同的工具包可用:

  • https://github.com/aws/aws-sdk-js
  • https://github.com/aws-amplify/amplify-js

  • 对于初学者来说,使用什么以及如何进行身份验证根本不清楚。理想情况下,我会像使用 firebase 一样使用它,只需让我的前端使用电子邮件和密码进行身份验证调用,然后接收某种类型的 token (仅在成功时),然后可以使用该 token 生成签名的 API调用。
    有人可以帮忙提供代码示例吗?

    最佳答案

    对困惑感到抱歉。
    AWS Cognito 用户池充当 身份提供者 .它支持所有用户管理(注册、登录、密码重置、用户删除等)。 Cognito 还支持 联合身份 (例如,已经拥有 Google/Facebook 帐户的用户可以登录)。在这种情况下,Cognito 使用 OAuth 与 Google/Facebook 对话。
    当我学习 Cognito/JWT token 时,我创建了一个简单的 JS/HTML 来了解它是如何工作的。既然你要了code,可以引用一下-https://github.com/ryandam9/Cognito-tokens .
    根据您的屏幕截图,您已经配置了一个用户池 - sls-notes-后端 .假设您将强制属性配置为 邮箱 .
    步骤 0 - 初始化
    创建用户池时,您会同时获得 userPoolId 和 appId。

    poolData = {
    UserPoolId: userPoolId,
    ClientId: appId
    };

    userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    第 1 步 - 使用电子邮件和密码注册用户 - 假设您的 UI 已经从用户那里捕获了这些详细信息,并且用户单击了“注册”按钮。
    enter image description here

    /**
    * Signup a User
    * @param e
    */
    function addUser(e) {
    signupMessage.style.display = 'none';
    signupMessage.className = '';

    e.preventDefault();

    let name = document.getElementById('name').value.trim();
    let email = document.getElementById('signup-email').value.trim();
    let password = document.getElementById('signup-password').value.trim();

    if (name.length === 0 || email === 0 || password === 0) {
    return;
    }

    let attributeList = [
    new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute({
    Name: 'given_name', Value: name
    }),
    ];

    userPool.signUp(email, password, attributeList, null, function (err, result) {
    if (err) {
    signupMessage.innerText = err;
    signupMessage.style.display = 'block';
    signupMessage.className = 'alert alert-danger';
    return;
    }

    cognitoUser = result.user;
    console.log('user name is ' + cognitoUser.getUsername());

    // Show a text box to enter Confirmation code
    document.getElementById('signup-btn').style.display = 'none';
    document.getElementById('code-block').style.display = 'block';
    document.getElementById('confirm-user-btn').style.display = 'inline-block';
    });
    }

    如果注册成功(它是有效的电子邮件,并且用户池中尚不存在该电子邮件,则会向提供的电子邮件发送确认代码。下一步是,让用户输入代码并确认其身份。
    第 3 步 - 确认用户
    enter image description here

    /**
    * Confirm the user by taking the Confirmation code.
    * @param e
    */
    function confirmUser(e) {
    e.preventDefault();
    let verificationCode = document.getElementById('code').value;

    cognitoUser.confirmRegistration(verificationCode, true, function (err, result) {
    if (err) {
    signupMessage.innerText = err;
    signupMessage.style.display = 'block';
    signupMessage.className = 'alert alert-danger';
    return;
    }

    signupMessage.innerText = result;
    signupMessage.style.display = 'block';
    signupMessage.className = 'alert alert-success';
    });
    }

    如果用户输入正确的代码,则确认其身份。此时,会为此用户在 Userpool 中创建一个条目。看起来像这样。
    enter image description here
    第 4 步 - 身份验证(登录)
    至此,用户注册完成。是时候让他登录了。请忽略下面代码中不必要的代码(获取和打印凭据的代​​码,解码部分)。 如果身份验证成功,Cognito 会向应用程序返回两种类型的 token - ID token 和访问 token 。这些仅对本次 session 和该用户有效。 更多细节在这里 - https://ryandam.net/aws/19-cognito-userpools/index.html#0

    /**
    * Signin user with Email and Password
    * @param e
    */
    function authenticateUser(e) {
    e.preventDefault();

    let email = document.getElementById('signin-email').value;
    let password = document.getElementById('signin-password').value;

    if (email.length === 0 || password === 0 || userPool === null || userPool === undefined) {
    signinMessage.innerText = 'Fill in all fields!';
    signinMessage.style.display = 'block';
    signinMessage.className = 'alert alert-danger';
    return;
    }

    let authenticationData = {
    Username: email,
    Password: password,
    };

    let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

    let userData = {
    Username: email,
    Pool: userPool
    };

    let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);

    cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
    signinMessage.innerText = 'Authentication Success!';
    signinMessage.style.display = 'block';
    signinMessage.className = 'alert alert-success';

    document.getElementById('token-section').style.display = 'block';
    document.getElementById('signin-btn').style.display = 'none';

    // Decode ID Token
    let idToken = result.idToken.jwtToken;
    document.getElementById('id-token').innerText = idToken;
    document.getElementById('decoded-id-token').appendChild(parseIdToken(idToken));

    // Decode Access Token
    let accessToken = result.getAccessToken().getJwtToken();
    document.getElementById('access-token').innerText = accessToken;
    document.getElementById('decoded-access-token').appendChild(parseAccessToken(accessToken));

    let cognitoUser = userPool.getCurrentUser();

    if (cognitoUser != null) {
    cognitoUser.getSession(function (err, result) {
    if (result) {
    // Set the region where your identity pool exists (us-east-1, eu-west-1)
    AWS.config.region = region;
    AWS.config.update({region: region});

    logins = {};
    let key = 'cognito-idp.us-east-2.amazonaws.com/' + userPoolId;
    logins[key] = result.getIdToken().getJwtToken();

    // Add the User's Id Token to the Cognito credentials login map.
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId,
    Logins: logins,
    });

    // Make the call to obtain credentials
    AWS.config.credentials.get(function () {
    // Credentials will be available when this function is called.
    var accessKeyId = AWS.config.credentials.accessKeyId;
    var secretAccessKey = AWS.config.credentials.secretAccessKey;
    var sessionToken = AWS.config.credentials.sessionToken;
    });

    if (s3BucketName.length > 0)
    listS3Bucket(s3BucketName);
    }
    });
    }
    },
    onFailure: function (err) {
    signinMessage.innerText = err;
    signinMessage.style.display = 'block';
    signinMessage.className = 'alert alert-danger';
    }
    }
    );
    }

    第 5 步 - 调用您已经创建的 API 端点 - 由于您已经创建了 授权人使用 Userpool 并且您使用 Authorization 作为 header ,您可以通过将 ID token 作为 Authorization header 传递来从 JS 调用端点。发生的情况是, token 由授权人验证。由于它是有效的,用户可以调用 API。**
    我没有 JS 代码,您可以从 CLI/Postman 测试您的 API,如下所示:
    enter image description here
    备注
    AWS Amplify 似乎是 Cognito 和其他服务的包装器。例如,当您调用其 CLI 命令时,Amplify 会为您设置用户池。如果您想了解 Amplify 如何与 Flutter 配合使用,可以引用此代码 - https://github.com/ryandam9/Auth-flutter-aws-amplify .
    我仍然在学习。我尽量做到准确。

    关于reactjs - Reactjs 中的 AWS Cognito 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65658404/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com