GithubHelp home page GithubHelp logo

amazon-cognito-identity-js's Introduction

Amazon Cognito Identity SDK for JavaScript

You can now use Amazon Cognito to easily add user sign-up and sign-in to your mobile and web apps. Your User Pool in Amazon Cognito is a fully managed user directory that can scale to hundreds of millions of users, so you don't have to worry about building, securing, and scaling a solution to handle user management and authentication.

Developer Preview: We welcome developer feedback on this project. You can reach us by creating an issue on the GitHub repository or posting to the Amazon Cognito Identity forums:

Introduction

The Amazon Cognito Identity SDK for JavaScript allows JavaScript enabled applications to sign-up users, authenticate users, view, delete, and update user attributes within the Amazon Cognito Identity service. Other functionality includes password changes for authenticated users and initiating and completing forgot password flows for unauthenticated users.

Setup

  1. Create an app for your user pool. Note that the generate client secret box must be unchecked because the JavaScript SDK doesn't support apps that have a client secret.

  2. Download and include the Amazon Cognito AWS SDK for JavaScript:

Note that the Amazon Cognito AWS SDK for JavaScript is just a slimmed down version of the AWS Javascript SDK namespaced as AWSCognito instead of AWS. It references only the Amazon Cognito Identity service. Simlar to the AWS JavaScript SDK, the config.credentials property needs to be populated (either globally for AWSCognito or per-service).

  1. Download and include the Amazon Cognito Identity SDK for JavaScript:
  1. Include the JavaScript BN library for BigInteger computations:
  1. Include the Stanford Javascript Crypto Library:

Please note, that by default the Stanford JavaScript Crypto Library doesn't include the bytes codec that the SDK uses so it must be included with the --with-codecBytes option when configuring the Stanford JavaScript Crypto Library.

  1. Include Moment.js, a JavaScript library used for date manipulation:
  1. Optionally, download and include the AWS JavaScript SDK in order to use other AWS services. The SDK is necessary in order to use AWS.CognitoIdentityCredentials:
    <script src="/path/to/jsbn.js"></script>
    <script src="/path/to/jsbn2.js"></script>
    <script src="/path/to/sjcl.js"></script>
    <script src="/path/to/moment.min.js"></script>
    <script src="/path/to/aws-cognito-sdk.min.js"></script>
    <script src="/path/to/amazon-cognito-identity.min.js"></script>
    <script src="/path/to/aws-sdk-2.3.5.js"></script>
    

Usage

Use case 1. Registering a user with the application. One needs to create a CognitoUserPool object by providing a UserPoolId and a ClientId and signing up by using a username, password, attribute list, and validation data.

    AWS.config.region = 'us-east-1'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: '...' // your identity pool id here
    });

    AWSCognito.config.region = 'us-east-1';
    AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: '...' // your identity pool id here
    });
        
    var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n',
                ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);

    var attributeList = [];
    
    var dataEmail = {
        Name : 'email',
        Value : '[email protected]'
    };
    var dataPhoneNumber = {
        Name : 'phone_number',
        Value : '+15555555555'
    };
    var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
    var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber);

    attributeList.push(attributeEmail);
    attributeList.push(attributePhoneNumber);

    userPool.signUp('username', 'password', attributeList, null, function(err, result){
        if (err) {
            alert(err);
            return;
        }
        cognitoUser = result.user;
        console.log('user name is ' + cognitoUser.getUsername());
    });

Use case 2. Confirming a registered, unauthenticated user using a confirmation code received via SMS.

    var poolData = {
            UserPoolId : 'us-east-1_TcoKGbf7n',
            ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
        };

    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    var userData = {
            Username : 'username',
            Pool : userPool
        };

    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.confirmRegistration('123456', true, function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 3. Resending a confirmation code via SMS for confirming registration for a unauthenticated user.

    cognitoUser.resendConfirmationCode(function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 4. Authenticating a user and establishing a user session with the Amazon Cognito Identity service.

    var authenticationData = {
        Username : 'username',
        Password : 'password',
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
    var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n',
                     ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    var userData = {
        Username : 'username',
        Pool : userPool
	   };
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log('access token + ' + result.getAccessToken().getJwtToken());
        },

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

    });

Use case 5. Retrieve user attributes for an authenticated user.

    cognitoUser.getUserAttributes(function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        for (i = 0; i < result.length; i++) {
            console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
        }
    });

Use case 6. Verify user attribute for an authenticated user.

    cognitoUser.getAttributeVerificationCode('email', {
        onSuccess: function (result) {
            console.log('call result: ' + result);
        },
        onFailure: function(err) {
            alert(err);
        },
        inputVerificationCode() {
            var verificationCode = prompt('Please input verification code: ' ,'');
            cognitoUser.verifyAttribute('email', verificationCode, this);
        }
    });

Use case 7. Delete user attribute for an authenticated user.

    var attributeList = [];
    attributeList.push('nickname');

    cognitoUser.deleteAttributes(attributeList, function(err, result) {
     	if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 8. Update user attributes for an authenticated user.

    var attributeList = [];
    var attribute = {
        Name : 'nickname',
        Value : 'joe'
    };
    var attribute = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(attribute);
    attributeList.push(attribute);

    cognitoUser.updateAttributes(attributeList, function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 9. Enabling MFA for a user on a pool that has an optional MFA setting for an authenticated user.

    cognitoUser.enableMFA(function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 10. Disabling MFA for a user on a pool that has an optional MFA setting for an authenticated user.

    cognitoUser.disableMFA(function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 11. Changing the current password for an authenticated user.

    cognitoUser.changePassword('oldPassword', 'newPassword', function(err, result) {
        if (err) {
            alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 12. Starting and completing a forgot password flow for an unauthenticated user.

    cognitoUser.forgotPassword({
        onSuccess: function (result) {
            console.log('call result: ' + result);
        },
        onFailure: function(err) {
            alert(err);
        },
        inputVerificationCode() {
            var verificationCode = prompt('Please input verification code ' ,'');
            var newPassword = prompt('Enter new password ' ,'');
            cognitoUser.confirmPassword(verificationCode, newPassword, this);
        }

Use case 13. Deleting an authenticated user.

    cognitoUser.deleteUser(function(err, result) {
        if (err) {
           	alert(err);
            return;
        }
        console.log('call result: ' + result);
    });

Use case 14. Signing out from the application.

    cognitoUser.signOut();

Use case 15. Retrieving the current user from local storage.

    var data = { UserPoolId : 'us-east-1_Iqc3ajYLS',
                 ClientId : '2lavgo9l86pkdu353sm7khjj1q'
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
    var cognitoUser = userPool.getCurrentUser();

    if (cognitoUser != null) {
        cognitoUser.getSession(function(err, session) {
            if (err) {
           	    alert(err);
                return;
            }
            console.log('session validity: ' + session.isValid());
        });
    }

Network Configuration

The Amazon Cognito Identity JavaScript SDK will make requests to the following endpoints

For most frameworks you can whitelist the domain by whitelisting all AWS endpoints with "*.amazonaws.com".

Change Log

v0.9.0:

  • Initial release. Developer preview.

amazon-cognito-identity-js's People

Contributors

horike37 avatar hyandell avatar shivankaul avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

aug-int

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.