简体   繁体   English

从浏览器 JS 向 AWS Cognito 用户池进行身份验证

[英]Authenticating to AWS Cognito User Pool from browser JS

I am building a proof of concept web app and would like to use an AWS Cognito User Pool as my user authentication mechanism.我正在构建一个概念证明 web 应用程序,并希望使用 AWS Cognito 用户池作为我的用户身份验证机制。 I have configured a user pool and a client app.我已经配置了一个用户池和一个客户端应用程序。 I have used the hosted UI to sign up a test user.我已经使用托管 UI 注册了一个测试用户。 Now I need to authenticate that user from the browser.现在我需要从浏览器验证该用户。

I have found two examples in AWS documentation ( here and here ) showing how to authenticate users against Cognito User Pools with browser-based javascript.我在 AWS 文档( 此处此处)中找到了两个示例,展示了如何使用基于浏览器的 javascript 针对 Cognito 用户池对用户进行身份验证。 I can't get either one to work for me.我不能让任何一个为我工作。

Here's my minimum-code demonstration HTML (two textboxes and a button):这是我的最小代码演示 HTML(两个文本框和一个按钮):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test Page</title>
    </head>
    <body>
        <input id="username" type="text" value="myUser"></input> <br>
        <input id="password" type="password" value="myPa55w0rd!"></input> <br>
        <button onclick="login()">Log In!</button>

        <script src="https://sdk.amazonaws.com/js/aws-sdk-2.726.0.js"></script>
        <script src="js/myscript.js"></script>
    </body>
</html>

Here's my myscript.js (version 1, from https://aws.amazon.com/blogs/mobile/accessing-your-user-pools-using-the-amazon-cognito-identity-sdk-for-javascript/ ):这是我的 myscript.js(版本 1,来自https://aws.amazon.com/blogs/mobile/accessing-your-user-pools-using-the-amazon-cognito-identity-sdk-for-javascript/ ):

function login() {
    AWS.config.region = "us-west-2";

    var poolData = {
        UserPoolId : 'us-west-2_redacted',
        ClientId : 'abcdefghijklmnopqrstuvwxyz'
    };
    var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData); <--Error here

    var authenticationData = {
        Username : document.getElementById("username").value,
        Password : document.getElementById("password").value
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.authenticationDetails(authenticationData); 

    var userData = {
        Username : document.getElementById("username").value,
        Pool: userPool
    };
    var cognitoUser = new AmazonCognito.CognitoIdentityServiceProvider.cognitoUser(userData);

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();

            /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
            var idToken = result.idToken.jwtToken;

            alert("Authentication successful!");
        },

        onFailure: function(err) {
            alert(err);
        },

    });
}

When I run this code, I get Uncaught TypeError: AWS.CognitoIdentityServiceProvider.CognitoUserPool is not a constructor in the line var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData);当我运行此代码时,我得到Uncaught TypeError: AWS.CognitoIdentityServiceProvider.CognitoUserPool is not a constructor in the line var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData); . . Sure enough, I don't see 'CognitoUserPool' anywhere in the aws-sdk-2.726.0.js file.果然,我在 aws-sdk-2.726.0.js 文件的任何地方都看不到“CognitoUserPool”。

Here is my second attempt, using the code example at https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html :这是我的第二次尝试,使用https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html的代码示例:

function login() {
    var authenticationData = {
        Username : document.getElementById("username").value,
        Password : document.getElementById("password").value
    }

    var authenticationDetails = new AmazonCognitoIdentity.authenticationDetails(authenticationData); <-- Error here
    var poolData = {
        UserPoolId : 'us-west-2_redacted',
        ClientId : 'abcdefghijklmnopqrstuvwxyz'
    };
    var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
    var userData = {
        Username : 'username',
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();

            /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
            var idToken = result.idToken.jwtToken;
        },

        onFailure: function(err) {
            alert(err);
        },
    });
}

When I run this code, I get Uncaught ReferenceError: AmazonCognitoIdentity is not defined .当我运行此代码时,我得到 Uncaught ReferenceError: AmazonCognitoIdentity is not defined Sure enough, the text 'AmazonCognitoIdentity' does not appear in the aws.sdk-2.726.0.js file.果然,文本“AmazonCognitoIdentity”没有出现在 aws.sdk-2.726.0.js 文件中。

I've been chasing my tail on this and so far haven't found a solution.我一直在追寻这个问题,到目前为止还没有找到解决方案。 I would very much like to avoid moving to the Amplify framework.我非常想避免转向 Amplify 框架。 That carries with it the cost of a steep learning curve for a new framework that I'd rather avoid, at least for now.这带来了我宁愿避免的新框架的陡峭学习曲线的成本,至少目前是这样。 In addition, I'm barely a JS programmer, and am certainly not a node programmer, so I'd have to climb the hill of learning node.js as well to make the move to Amplify.此外,我几乎不是一个 JS 程序员,当然也不是一个节点程序员,所以我必须爬上学习 node.js 的小山,才能转向 Amplify。

Is it possible to authenticate a user with simple client-side Javascript, without using Amplify?是否可以在不使用 Amplify 的情况下使用简单的客户端 Javascript 对用户进行身份验证? If so, I'd greatly appreciate a full working example (or someone pointing out what I'm doing wrong.)如果是这样,我将非常感谢一个完整的工作示例(或有人指出我做错了什么。)

For anyone who's coming after me with this problem, I found a solution.对于任何追随我这个问题的人,我找到了解决方案。 Whether it's the right solution or not, I don't know.这是否是正确的解决方案,我不知道。 Best of luck to y'all:祝大家好运:

function login() {
    AWS.config.update({region : "us-west-2"});

    const payload = {
        AuthFlow: "USER_PASSWORD_AUTH",
        ClientId: "abcdefghijklmnopqrstuvwxyz",
        AuthParameters : {
            USERNAME: document.getElementById('username').value,
            PASSWORD: document.getElementById('password').value
        }
    }

    var cognito = new AWS.CognitoIdentityServiceProvider();
    cognito.initiateAuth(payload, function(err,data) {
        if (err) {
            alert("Error: " + err);
        }
        else {
            alert("Success!");
        }
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Google作为身份提供者在AWS Cognito用户/身份池中对用户进行身份验证 - Authenticating user in AWS Cognito User/Identity Pool with Google as identity provider 如何使用 AWS Cognito 中的现有用户池生成 aws-exports.js? - How to generate aws-exports.js with existing User Pool in AWS Cognito? AWS Cognito - 从浏览器应用程序邀请用户 (adminCreateUser) - AWS Cognito - invite user from browser application (adminCreateUser) AWS - 在现有 React web 应用程序上使用用户名和密码从现有 Cognito 用户池获取用户令牌 - AWS - Get user token from an existing Cognito User Pool with username and password on an existing React web app 如何使用AWS Cognito在浏览器中验证用户? - How to authenticate user in browser using AWS Cognito? 在AWS Cognito用户池中为Facebook注册创建帐户 - create account in aws cognito user pool for facebook sign up 如何针对AWS Cognito用户池进行身份验证 - How do I authenticate against an AWS Cognito User Pool 在node.js中使用Cognito用户池创建用户 - Creating a User With cognito User Pool in node.js 如何为属于多个用户池组的 AWS Cognito 用户切换 IAM 角色? - How to switch IAM roles for AWS Cognito User belonging to multiple User Pool groups? 有没有办法使用 AWS Amplify 库 (JavaScript) 在没有认知用户池和身份池的情况下访问 s3 存储桶? - Is there a way to use AWS Amplify library (JavaScript) to access s3 bucket without cognito user poool and identity pool?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM