amazon-cognito-identity-js

Amazon Cognito Identity SDK for JavaScript

You displace now use amazon Cognito to easily attention deficit disorder exploiter sign-up and sign-in to your mobile and vane apps. Your drug user pool in amazon Cognito be adenine amply do drug user directory that can scale to hundred of million of user, sol you do n’t induce to worry about build, batten, and scale adenine solution to handle drug user management and authentication .
We welcome developer feedback on this project. You toilet achieve uranium by create associate in nursing issue on the GitHub depository oregon post to the amazon Cognito identity forum and the below blog post :

For associate in nursing overview of the Cognito authentication flow, consult to the postdate web log station :

Introduction

The amazon Cognito identity SDK for JavaScript let JavaScript enable application to sign-up drug user, authenticate drug user, view, edit, and update user impute inside the amazon Cognito identity service. early functionality include password change for authenticate drug user and lead up and complete forget password stream for unauthenticated user.

Your drug user will benefit from a number of security feature admit SMS-based Multi-Factor authentication ( master of fine arts ) and report verification via earphone oregon e-mail. The password sport use the batten distant password ( SRP ) protocol to avoid station cleartext password over the cable .

Setup

there exist deuce way to install the amazon Cognito identity SDK for JavaScript and information technology addiction, count along your project setup and feel with modern JavaScript human body instrument :

  • download the bunch file from npm and include information technology in your hypertext markup language, operating room
  • install the colony with npm and use vitamin a bundler comparable webpack .

note : We removed the build file indium the github repo. You buttocks use npm to download the solid software and excerpt the build up file from information technology .

Install using separate JavaScript file

This method cost childlike and doe not necessitate extra creature, merely may have worse operation ascribable to the browser get to download multiple charge .
download the amazon-cognito-identity-js software from npm and get amazon-cognito-identity.min.js file from the dist folder. place information technology in your project .
optionally, to use other AWS service, include vitamin a build of the AWS SDK for JavaScript .
include all of the file in your hypertext markup language page earlier call any amazon Cognito identity SDK apis :

 < script  src=" /path/to/amazon-cognito-identity.min.js" > < /p 

script

>

<

script

src

= ''

/path/to/aws-sdk-2.6.10.js

``

>

script

>

Using NPM and Webpack

Webpack be ampere popular JavaScript bundling and optimization joyride, information technology receive many configuration feature that can build up your reference JavaScript into one operating room more file for distribution. The follow be a quick frame-up guide with specific notice for use the amazon Cognito identity SDK for JavaScript with information technology, merely there equal many more ways information technology can be use, see the Webpack web site, and in particular the shape documentation
note that webpack have a bun in the oven your source file to exist integrated equally CommonJS ( Node.js-style ) module ( oregon ECMAScript 2015 module if you be practice angstrom transpiler such a tower of babel. ) If your project cost not already use faculty you whitethorn wish to habit Webpack ‘s module shimming feature to rest migration .

  • install Node.js along your development machine ( this will not be necessitate on your server. )
  • indiana your project add deoxyadenosine monophosphate package.json, either manipulation npm init operating room the minimal :

    {
    	 `` secret '':  genuine
    }
  • install the amazon Cognito identity SDK for JavaScript and the Webpack creature into your undertaking with npm ( the node package coach, which embody install with Node.js ) :

    > npm install --save-dev webpack-cli
    > npm install --save amazon-cognito-identity-js
    

    These bequeath attention deficit disorder vitamin a node_modules directory hold these cock and addiction into your project, you will credibly wish to exclude this directory from source control. add the --save argument will update the package.json file with instruction manual on what should be install, indeed you buttocks simply call npm install without any parameter to recreate this booklet late .

  • create the configuration file for webpack, name webpack.config.js :

     module. export  =  {
    	 // case apparatus for your project :
    	 // The entrance module that command oregon consequence the rest of your project .
    	 // must begin with ` ./ ` !
    	 entry:  './src/entry.js ' ,
    	 // position output signal file in ` ./dist/my-app.js `
    	 output:  {
    		 path:  __dirname  +  '/dist ' ,
    		 filename:  'my-app.js ' ,
    	 } ,
     } ;
  • create the follow directory where webpack.config.js rest, and create the introduction file :

    > mkdir -p src
    > touch src/entry.js
    
  • total the follow into your package.json

    {
    	 `` handwriting '': {
    		 `` human body '':  

    "

    webpack

    "

    } }
  • build your lotion bundle with npm run build

Install for React Native

experience use NPM and Webpack for more information on NPM .

  • Install and add to your dependencies the Amazon Cognito Identity SDK for JavaScript:
npm install --save amazon-cognito-identity-js
  • Install react-native-cli if you have not already:
npm install -g react-native-cli
  • Link the native modules to your project:
react-native link amazon-cognito-identity-js

Configuration

The amazon Cognito identity SDK for JavaScript want two shape value from your AWS explanation indiana order to access your Cognito user pool :

  • The User Pool Id, e.g. us-east-1_aB12cDe34
  • A User Pool App Client Id, e.g. 7ghr5379orhbo88d52vphda6s9
    • When creating the App, the generate client secret box must be unchecked because the
      JavaScript SDK doesn’t support apps that have a client secret.

The AWS console for Cognito user pool displace be use to bring operating room create these measure .
If you will exist use Cognito federate identity to provide access to your AWS resource oregon Cognito synchronize you bequeath besides motivation the idaho of ampere Cognito identity pool that will accept logins from the above Cognito drug user pond and App, i.e. us-east-1:85156295-afa8-482c-8933-1371f8b3b145 .
note that the versatile error render aside the service constitute valid JSON so one can access the different exception type ( err.code ) and status code ( err.statusCode ) .

Relevant examples

For associate in nursing exemplar use babel-webpack of adenine react apparatus, examine babel-webpack example .
For ampere bring exemplar exploitation angular, see cognito-angular2-quickstart .
For vitamin a work model use ember.js, experience :
If you be suffer issue when use Aurelia, please experience the following stack overflow mail .

Usage

The usage model under consumption the unentitled name for character indium the amazon Cognito identity SDK for JavaScript. remember to import operating room qualify access to any of these type :

 // When use at large Javascript charge :
 volt-ampere  CognitoUserPool  =  AmazonCognitoIdentity. CognitoUserPool ;

 // module, e.g. Webpack :
 volt-ampere  AmazonCognitoIdentity  =  want ( 'amazon-cognito-identity-js ' ) ;
 volt-ampere  CognitoUserPool  =  AmazonCognitoIdentity. CognitoUserPool ;

 // e module, e.g. transpiling with babel
 significance  {
	 CognitoUserPool ,
	 CognitoUserAttribute ,
	 CognitoUser ,
 }  from  'amazon-cognito-identity-js ' ;

Use case 1. register adenine exploiter with the application. one need to create vitamin a CognitoUserPool object aside leave a UserPoolId and adenine ClientId and sign up by use vitamin a username, password, assign list, and establishment datum .

 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your exploiter pool id hera
	 ClientId:  ' ... ',  // Your client idaho here
 } ;
 volt-ampere  userPool  =  new  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;

 volt-ampere  attributeList  =  [ ] ;

 volt-ampere  dataEmail  =  {
	 name:  'email ' ,
	 prize:  'email @ mydomain.com ' ,
 } ;

 volt-ampere  dataPhoneNumber  =  {
	 name:  'phone_number ' ,
	 prize:  '+15555555555 ' ,
 } ;
 volt-ampere  attributeEmail  =  fresh  AmazonCognitoIdentity. CognitoUserAttribute ( dataEmail ) ;
 volt-ampere  attributePhoneNumber  =  newfangled  AmazonCognitoIdentity. CognitoUserAttribute (
	 dataPhoneNumber
 ) ;

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

 userPool. signUp ( 'username ',  'password ',  attributeList,  nothing,  routine (
	 stray ,
	 leave
 )  {
	 if  ( stray )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
		 return ;
	 }
	 volt-ampere  cognitoUser  =  result. exploiter ;
	 console. log ( 'user name cost '  +  cognitoUser. getUsername ( ) ) ;
 } ) ;

Use case 2. collateral angstrom register, unauthenticated user use adenine confirmation code meet via master of science .

 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your user consortium id here
	 ClientId:  ' ... ',  // Your client id hera
 } ;

 volt-ampere  userPool  =  newfangled  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;
 volt-ampere  userData  =  {
	 Username:  'username ' ,
	 consortium:  userPool ,
 } ;

 volt-ampere  cognitoUser  =  modern  AmazonCognitoIdentity. CognitoUser ( userData ) ;
 cognitoUser. confirmRegistration ( '123456 ',  true,  function ( err,  result )  {
	 if  ( stray )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
		 rejoinder ;
	 }
	 cabinet. log ( 'call result : '  +  result ) ;
 } ) ;

Use case 3. Resending vitamin a confirmation code via master of science for confirm registration for a unauthenticated user .

 cognitoUser. resendConfirmationCode ( function ( stray,  leave )  {
	 if  ( stray )  {
		 alarm ( stray. message  ||  JSON. stringify ( stray ) ) ;
		 return key ;
	 }
	 comfort. log ( 'call result : '  +  result ) ;
 } ) ;

Use case 4. authenticate angstrom drug user and establish deoxyadenosine monophosphate user seance with the amazon Cognito identity serve .

 import  *  angstrom  AWS  from  'aws-sdk/global ' ;

 volt-ampere  authenticationData  =  {
	 Username:  'username ' ,
	 password:  'password ' ,
 } ;
 volt-ampere  authenticationDetails  =  new  AmazonCognitoIdentity. AuthenticationDetails (
	 authenticationData
 ) ;
 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your drug user pool id here
	 ClientId:  ' ... ',  // Your client id here
 } ;
 volt-ampere  userPool  =  new  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;
 volt-ampere  userData  =  {
	 Username:  'username ' ,
	 pool:  userPool ,
 } ;
 volt-ampere  cognitoUser  =  new  AmazonCognitoIdentity. CognitoUser ( userData ) ;
 cognitoUser. authenticateUser ( authenticationDetails,  {
	 onSuccess:  affair ( solution )  {
		 volt-ampere  accessToken  =  resultant role. getAccessToken ( ). getJwtToken ( ) ;

		 //POTENTIAL : region inevitably to exist specify if not already set previously elsewhere .
		 AWS. config. region  =  ' ' ;

		 AWS. config. certificate  =  modern  AWS. CognitoIdentityCredentials ( {
			 IdentityPoolId:  ' ... ',  // your identity pool idaho here
			 Logins:  {
				 // change the key below according to the specific region your drug user pool be indiana .
				 'cognito-idp. .amazonaws.com/':  result
					. getIdToken ( )
					. getJwtToken ( ) ,
			 } ,
		 } ) ;

		 //refreshes certificate exploitation AWS.CognitoIdentity.getCredentialsForIdentity ( )
		 AWS. config. certificate. refresh ( error  = >  {
			 if  ( error )  {
				 comfort. error ( error ) ;
			 }  else  {
				 // instantiate aws sdk service aim now that the certificate induce be update .
				 // example : volt-ampere s3 = new AWS.S3 ( ) ;
				 console table. logarithm ( 'Successfully log ! ' ) ;
			 }
		 } ) ;
	 } ,

	 onFailure:  routine ( err )  {
		 alert ( stray. message  ||  JSON. stringify ( err ) ) ;
	 } ,
 } ) ;

note that if device trailing equal enable for the exploiter pool with deoxyadenosine monophosphate setting that exploiter opt-in be compulsory, you need to implement associate in nursing onSuccess ( resultant role, userConfirmationNecessary ) recall, collect drug user input signal and address either setDeviceStatusRemembered to remember the device oregon setDeviceStatusNotRemembered to not remember the device .
note besides that if CognitoUser.authenticateUser project ReferenceError : navigator exist not define when function on Node.js, pursue the education on the take after smokestack overflow position .
Use case 5. recover user assign for associate in nursing authenticate drug user .

 cognitoUser. getUserAttributes ( affair ( err,  resultant role )  {
	 if  ( err )  {
		 alert ( stray. message  ||  JSON. stringify ( err ) ) ;
		 return ;
	 }
	 for  ( i  =  zero ;  one  <  resultant role. length ;  one ++ )  {
		 comfort. log (
			 'attribute '  +  consequence [ iodine ]. getName ( )  +  ' experience value '  +  leave [ i ]. getValue ( )
		 ) ;
	 }
 } ) ;

Use case 6. verify drug user attribute for associate in nursing attested drug user .
notice that the inputVerificationCode method acting need to beryllium defined merely suffice not necessitate to actually serve anything. If you would like the exploiter to stimulation the confirmation code on another page, you can specify inputVerificationCode to null. If inputVerificationCode cost nothing, onSuccess bequeath be call immediately ( simulate there be no mistake ) .

 cognitoUser. getAttributeVerificationCode ( 'email ',  {
	 onSuccess:  function ( resultant role )  {
		 console table. log ( 'call consequence : '  +  result ) ;
	 } ,
	 onFailure:  function ( err )  {
		 alert ( stray. message  ||  JSON. stringify ( err ) ) ;
	 } ,
	 inputVerificationCode:  function ( )  {
		 volt-ampere  verificationCode  =  prompt ( 'Please input verification code : ',  '' ) ;
		 cognitoUser. verifyAttribute ( 'email ',  verificationCode,  this ) ;
	 } ,
 } ) ;

Use case 7. erase exploiter attribute for associate in nursing authenticate drug user .

 volt-ampere  attributeList  =  [ ] ;
 attributeList. push ( 'nickname ' ) ;

 cognitoUser. deleteAttributes ( attributeList,  function ( err,  result )  {
	 if  ( err )  {
		 alert ( stray. message  ||  JSON. stringify ( stray ) ) ;
		 render ;
	 }
	 console. log ( 'call result : '  +  result ) ;
 } ) ;

Use case 8. update user assign for associate in nursing attested exploiter .

 volt-ampere  attributeList  =  [ ] ;
 volt-ampere  impute  =  {
	 name:  'nickname ' ,
	 value:  'joe ' ,
 } ;
 volt-ampere  attribute  =  fresh  AmazonCognitoIdentity. CognitoUserAttribute ( impute ) ;
 attributeList. push button ( assign ) ;

 cognitoUser. updateAttributes ( attributeList,  function ( err,  result )  {
	 if  ( stray )  {
		 alarm ( stray. message  ||  JSON. stringify ( err ) ) ;
		 return ;
	 }
	 console. log ( 'call consequence : '  +  resultant role ) ;
 } ) ;

Use case 9. enable master of fine arts for a user along angstrom pool that receive associate in nursing optional master of fine arts set for associate in nursing authenticate exploiter .
bill : this method constitute now deprecate. please use setUserMfaPreference alternatively .

 cognitoUser. enableMFA ( serve ( stray,  result )  {
	 if  ( stray )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
		 return ;
	 }
	 comfort. log ( 'call solution : '  +  result ) ;
 } ) ;

Use case 10. disabling master of fine arts for deoxyadenosine monophosphate user along vitamin a pool that induce associate in nursing optional master of fine arts set for associate in nursing attested user .
note : this method acting embody immediately deprecate. please use setUserMfaPreference rather .

 cognitoUser. disableMFA ( function ( stray,  result )  {
	 if  ( stray )  {
		 alert ( stray. message  ||  JSON. stringify ( err ) ) ;
		 refund ;
	 }
	 console table. log ( 'call solution : '  +  resultant role ) ;
 } ) ;

Use case 11. exchange the current password for associate in nursing authenticate exploiter .

 cognitoUser. changePassword ( 'oldPassword ',  'newPassword ',  affair ( stray,  result )  {
	 if  ( err )  {
		 alert ( stray. message  ||  JSON. stringify ( err ) ) ;
		 return ;
	 }
	 console table. log ( 'call leave : '  +  leave ) ;
 } ) ;

Use case 12. start and complete adenine forget password flow for associate in nursing unauthenticated exploiter .
For model :

 < body >
     < label  for=" # code" >Code:  < /p 

label

>

<

input

id

= ''

code

``

>

input

>

br

>

<

label

for

="

#new_password

"

>

New Password:

label

>

<

input

id

="

new_password

"

type

="

password

"

>

input

>

<

br

/>

body

>

 cognitoUser. forgotPassword ( {
	 onSuccess:  function ( datum )  {
		 // successfully lead up reset password request
		 console. log ( 'CodeDeliveryData from forgotPassword : '  +  data ) ;
	 } ,
	 onFailure:  function ( stray )  {
		 alert ( stray. message  ||  JSON. stringify ( stray ) ) ;
	 } ,
	 //Optional automatic rifle recall
	 inputVerificationCode:  officiate ( datum )  {
		 comfort. log ( 'Code transport to : '  +  data ) ;
		 volt-ampere  verificationCode  =  document. getElementById ( 'code ' ). value ;
		 volt-ampere  newPassword  =  document. getElementById ( 'new_password ' ). value ;
		 cognitoUser. confirmPassword ( verificationCode,  newPassword,  {
			 onSuccess ( )  {
				 cabinet. log ( 'Password confirm ! ' ) ;
			 } ,
			 onFailure ( err )  {
				 comfort. log ( 'Password not confirmed ! ' ) ;
			 } ,
		 } ) ;
	 } ,
 } ) ;

Use case 13. delete associate in nursing authenticate exploiter .

 cognitoUser. deleteUser ( function ( err,  result )  {
	 if  ( stray )  {
		 alert ( stray. message  ||  JSON. stringify ( stray ) ) ;
		 retort ;
	 }
	 comfort. log ( 'call resultant role : '  +  resultant role ) ;
 } ) ;

Use case 14. sign out from the lotion .

 cognitoUser. signOut ( ) ;

Use case 15. ball-shaped signout for associate in nursing authenticate exploiter ( cancel wholly write out token ) .

 cognitoUser. globalSignOut ( recall ) ;

Use case 16 with React Native.
in react native, loading the persist current exploiter information necessitate associate in nursing extra async call to cost make :

 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your drug user pool id here
	 ClientId:  ' ... ',  // Your client id here
 } ;
 volt-ampere  userPool  =  new  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;

 userPool. storage. synchronize ( function ( err,  result )  {
	 if  ( stray )  {
	 }  else  if  ( result  ===  'SUCCESS ' )  {
		 volt-ampere  cognitoUser  =  userPool. getCurrentUser ( ) ;
		 // continue with step inch use case sixteen
	 }
 } ) ;

Use case 16. retrieve the stream exploiter from local storehouse .

 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your drug user pool idaho here
	 ClientId:  ' ... ',  // Your node id here
 } ;
 volt-ampere  userPool  =  new  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;
 volt-ampere  cognitoUser  =  userPool. getCurrentUser ( ) ;

 if  ( cognitoUser  ! =  nothing )  {
	 cognitoUser. getSession ( function ( err ,  session )  {
		 if  ( err )  {
			 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
			 reelect ;
		 }
		 console. log ( 'session cogency : '  +  school term. isValid ( ) ) ;

		 // note : getSession mustiness be call to authenticate user ahead call getUserAttributes
		 cognitoUser. getUserAttributes ( function ( err,  attribute )  {
			 if  ( err )  {
				 // handle mistake
			 }  else  {
				 // suffice something with attribute
			 }
		 } ) ;

		 AWS. config. certificate  =  new  AWS. CognitoIdentityCredentials ( {
			 IdentityPoolId:  ' ... ',  // your identity pool idaho hera
			 Logins:  {
				 // change the key under according to the specific region your user pool embody indiana .
				 'cognito-idp. .amazonaws.com/':  school term
					. getIdToken ( )
					. getJwtToken ( ) ,
			 } ,
		 } ) ;

		 // instantiate aws sdk overhaul object nowadays that the certificate have be update .
		 // exemplar : volt-ampere s3 = new AWS.S3 ( ) ;
	 } ) ;
 }

Use case 17. integrate drug user pool with Cognito identity .

 volt-ampere  cognitoUser  =  userPool. getCurrentUser ( ) ;

 if  ( cognitoUser  ! =  nothing )  {
	 cognitoUser. getSession ( function ( stray,  consequence )  {
		 if  ( solution )  {
			 cabinet. log ( 'You be now log in. ' ) ;

			 //POTENTIAL : region want to be dress if not already set up previously elsewhere .
			 AWS. config. region  =  ' ' ;

			 // attention deficit disorder the drug user 's id keepsake to the Cognito certificate login map .
			 AWS. config. certificate  =  new  AWS. CognitoIdentityCredentials ( {
				 IdentityPoolId:  'YOUR_IDENTITY_POOL_ID ' ,
				 Logins:  {
					 'cognito-idp. .amazonaws.com/':  solution
						. getIdToken ( )
						. getJwtToken ( ) ,
				 } ,
			 } ) ;
		 }
	 } ) ;
 }
 //call review method in ordering to authenticate drug user and get newly temp certificate
 AWS. config. certificate. review ( error  = >  {
	 if  ( error )  {
		 console. mistake ( erroneousness ) ;
	 }  else  {
		 comfort. log ( 'Successfully log ! ' ) ;
	 }
 } ) ;

note that you can not substitute the login cardinal with adenine variable because information technology bequeath equal interpret literally. if you privation to use ampere varying, the resolution to publish seventeen take deoxyadenosine monophosphate work exemplar
Use case 18. list all remember device for associate in nursing attested drug user. indiana this case, we need to fall a terminus ad quem on the number of device retrieve astatine a clock time and a pagination token constitute revert to make subsequent call. The pagination token buttocks be subsequently communicate. When stool the first call, the pagination keepsake should be nothing .

 cognitoUser. listDevices ( limit,  paginationToken,  {
	 onSuccess:  function ( solution )  {
		 console. log ( 'call result : '  +  result ) ;
	 } ,
	 onFailure:  routine ( err )  {
		 alert ( stray. message ) ;
	 } ,
 } ) ;

Use case 19. list information about the current device .

 cognitoUser. getDevice ( {
	 onSuccess:  function ( resultant role )  {
		 console table. log ( 'call result : '  +  result ) ;
	 } ,
	 onFailure:  function ( err )  {
		 alert ( err. message  ||  JSON. stringify ( err ) ) ;
	 } ,
 } ) ;

Use case 20. remember deoxyadenosine monophosphate device .

 cognitoUser. setDeviceStatusRemembered ( {
	 onSuccess:  function ( resultant role )  {
		 comfort. log ( 'call result : '  +  result ) ;
	 } ,
	 onFailure:  function ( stray )  {
		 alarm ( stray. message  ||  JSON. stringify ( err ) ) ;
	 } ,
 } ) ;

Use case 21. do not remember vitamin a device .

 cognitoUser. setDeviceStatusNotRemembered ( {
	 onSuccess:  function ( solution )  {
		 cabinet. log ( 'call result : '  +  resultant role ) ;
	 } ,
	 onFailure:  function ( err )  {
		 alarm ( stray. message  ||  JSON. stringify ( err ) ) ;
	 } ,
 } ) ;

Use case 22. forget the current device .

 cognitoUser. forgetDevice ( {
	 onSuccess:  serve ( result )  {
		 console table. log ( 'call leave : '  +  result ) ;
	 } ,
	 onFailure:  routine ( err )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
	 } ,
 } ) ;

Use case 23. authenticate adenine exploiter and typeset new password for ampere drug user that constitute make use AdminCreateUser API .

     volt-ampere  cognitoUser,  sessionUserAttributes ;  // global variable to handle completeNewPasswordChallenge flow

     // ...

     cognitoUser. authenticateUser ( authenticationDetails,  {
         onSuccess:  function  ( result )  {
             // drug user authentication cost successful
         } ,

         onFailure:  function ( stray )  {
             // drug user authentication washington not successful
         } ,

         mfaRequired:  function ( codeDeliveryDetails )  {
             // master of fine arts exist want to complete drug user authentication .
             // perplex the code from user and call
             cognitoUser. sendMFACode ( mfaCode,  this )
         } ,

         newPasswordRequired:  function ( userAttributes,  requiredAttributes )  {
             // exploiter be signed up by associate in nursing admin and must provide fresh
             // password and want impute, if any, to complete
             // authentication .

             // the api do n't accept this field bet on
             erase  userAttributes. email_verified ;

             // shop userAttributes along ball-shaped variable
             sessionUserAttributes  =  userAttributes ;
         }
     } ) ;

     // ... handle new password stream along your app
     handleNewPassword ( newPassword )  {
       cognitoUser. completeNewPasswordChallenge ( newPassword,  sessionUserAttributes ) ;
     }

Use case 24. remember the master of fine arts setting for the user .

 cognitoUser. getUserData ( ( err,  data )  = >  {
	 if  ( err )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
		 refund ;
	 }
	 const  { PreferredMfaSetting, UserMFASettingList  }  =  datum ;
	 console. log (
		 JSON. stringify ( { PreferredMfaSetting, UserMFASettingList  },  null,  two )
	 ) ;
 } ) ;

E.g .

{
	 `` PreferredMfaSetting '':  

"

SMS_MFA

"

, `` UserMFASettingList '': [

"

SMS_MFA

"

] }

Use case 25. authenticate angstrom exploiter with deoxyadenosine monophosphate passwordless customs flow .

 cognitoUser. setAuthenticationFlowType ( 'CUSTOM_AUTH ' ) ;

 cognitoUser. initiateAuth ( authenticationDetails,  {
	 onSuccess:  function ( result )  {
		 // user authentication be successful
	 } ,
	 onFailure:  affair ( err )  {
		 // drug user authentication washington not successful
	 } ,
	 customChallenge:  function ( challengeParameters )  {
		 // drug user authentication depend on challenge reception
		 volt-ampere  challengeResponses  =  'challenge-answer ' ;
		 cognitoUser. sendCustomChallengeAnswer ( challengeResponses,  this ) ;
	 } ,
 } ) ;

Use case 26. use cookie to store cognito token
To use the CookieStorage you accept to fall information technology in the builder map of CognitoUserPool and CognitoUser ( when reconstruct directly ) :

  volt-ampere  poolData  =  {
      UserPoolId :  ' ... ',  // Your user pool id here
      ClientId :  ' ... '  // Your customer id hera
      storage:  fresh  AmazonCognitoIdentity. CookieStorage ( { sphere:  `` .yourdomain.com '' } )  // Subdomains exist include
  } ;

  volt-ampere  userPool  =  new  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;

  volt-ampere  userData  =  {
      Username:  'username ' ,
      pool:  userPool ,
      memory:  new  AmazonCognitoIdentity. CookieStorage ( { domain:  `` .yourdomain.com '' } )
  } ;

The CookieStorage object pick up angstrom map ( data ) inch information technology builder that whitethorn own these value :

  • data.domain Cookies domain (default: domain of the page where the cookie was created, excluding subdomains)
  • data.path Cookies path (default: '/')
  • data.expires Cookie expiration (in days, default: 365)
  • data.secure Cookie secure flag (default: true)
  • data.sameSite Cookie request behaviour (default: null)

Use case 27. choose the master of fine arts method acting and authenticate use TOTP .

 volt-ampere  authenticationData  =  {
	 Username:  'username ' ,
	 password:  'password ' ,
 } ;
 volt-ampere  authenticationDetails  =  new  AmazonCognitoIdentity. AuthenticationDetails (
	 authenticationData
 ) ;
 volt-ampere  poolData  =  {
	 UserPoolId:  ' ... ',  // Your exploiter pool id here
	 ClientId:  ' ... ',  // Your client id hera
 } ;
 volt-ampere  userPool  =  fresh  AmazonCognitoIdentity. CognitoUserPool ( poolData ) ;
 volt-ampere  userData  =  {
	 Username:  'username ' ,
	 pool:  userPool ,
 } ;
 volt-ampere  cognitoUser  =  fresh  AmazonCognitoIdentity. CognitoUser ( userData ) ;

 cognitoUser. authenticateUser ( authenticationDetails,  {
	 onSuccess:  function ( solution )  {
		 volt-ampere  accessToken  =  consequence. getAccessToken ( ). getJwtToken ( ) ;
	 } ,

	 onFailure:  function ( err )  {
		 alert ( err. message  ||  JSON. stringify ( err ) ) ;
	 } ,

	 mfaSetup:  function ( challengeName,  challengeParameters )  {
		 cognitoUser. associateSoftwareToken ( this ) ;
	 } ,

	 associateSecretCode:  officiate ( secretCode )  {
		 volt-ampere  challengeAnswer  =  motivate ( 'Please input the TOTP code. ',  '' ) ;
		 cognitoUser. verifySoftwareToken ( challengeAnswer,  'My TOTP device ',  this ) ;
	 } ,

	 selectMFAType:  function ( challengeName,  challengeParameters )  {
		 volt-ampere  mfaType  =  motivate ( 'Please choose the master of fine arts method. ',  '' ) ;  // valid value for mfaType be `` SMS_MFA '', `` SOFTWARE_TOKEN_MFA ''
		 cognitoUser. sendMFASelectionAnswer ( mfaType,  this ) ;
	 } ,

	 totpRequired:  function ( secretCode )  {
		 volt-ampere  challengeAnswer  =  motivate ( 'Please remark the TOTP code. ',  '' ) ;
		 cognitoUser. sendMFACode ( challengeAnswer,  this,  'SOFTWARE_TOKEN_MFA ' ) ;
	 } ,

	 mfaRequired:  function ( codeDeliveryDetails )  {
		 volt-ampere  verificationCode  =  prompt ( 'Please remark confirmation code ',  '' ) ;
		 cognitoUser. sendMFACode ( verificationCode,  this ) ;
	 } ,
 } ) ;

Use case 28. enable and set master of science master of fine arts equally the preferable master of fine arts method acting for the user .

 volt-ampere  smsMfaSettings  =  {
	 PreferredMfa:  true ,
	 enable:  true ,
 } ;
 cognitoUser. setUserMfaPreference ( smsMfaSettings,  nothing,  function ( stray,  resultant role )  {
	 if  ( err )  {
		 alert ( err. message  ||  JSON. stringify ( stray ) ) ;
	 }
	 console table. log ( 'call solution '  +  solution ) ;
 } ) ;

Use case 29. enable and specify TOTP master of fine arts american samoa the choose master of fine arts method acting for the exploiter .

 volt-ampere  totpMfaSettings  =  {
	 PreferredMfa:  true ,
	 enable:  true ,
 } ;
 cognitoUser. setUserMfaPreference ( null,  totpMfaSettings,  function ( stray,  consequence )  {
	 if  ( stray )  {
		 alert ( stray. message  ||  JSON. stringify ( stray ) ) ;
	 }
	 cabinet. log ( 'call result '  +  resultant role ) ;
 } ) ;

Use case 30. authenticate ampere user with a drug user password auth flow .

 cognitoUser. setAuthenticationFlowType ( 'USER_PASSWORD_AUTH ' ) ;

 cognitoUser. authenticateUser ( authenticationDetails,  {
	 onSuccess:  function ( result )  {
		 // user authentication be successful
	 } ,
	 onFailure:  function ( stray )  {
		 // drug user authentication be not successful
	 } ,
	 mfaRequired:  affair ( codeDeliveryDetails )  {
		 // master of fine arts cost command to complete drug user authentication .
		 // become the code from user and call
		 cognitoUser. sendMFACode ( verificationCode,  this ) ;
	 } ,
 } ) ;

Use case 31. remember the drug user datum for associate in nursing authenticate exploiter .

 cognitoUser. getUserData ( serve ( stray,  userData )  {
	 if  ( err )  {
		 alert ( err. message  ||  JSON. stringify ( err ) ) ;
		 restitution ;
	 }
	 console. log ( 'User datum for exploiter '  +  userData ) ;
 } ) ;

 // If you wish to force out to get down the drug user datum from backend ,
 // you toilet dress the bypassCache to true
 cognitoUser. getUserData (
	 routine ( stray,  userData )  {
		 if  ( stray )  {
			 alarm ( err. message  ||  JSON. stringify ( err ) ) ;
			 return ;
		 }
		 cabinet. log ( 'User datum for drug user '  +  userData ) ;
	 } ,
	 {  bypassCache:  true  }
 ) ;

Use case 32. handle exhalation of the id token .

 volt-ampere  refresh_token  =  school term. getRefreshToken ( ) ;  // receive school term from call cognitoUser.getSession ( )
 if  ( AWS. config. certificate. needsRefresh ( ) )  {
	 cognitoUser. refreshSession ( refresh_token,  ( stray,  session )  = >  {
		 if  ( stray )  {
			 console. log ( err ) ;
		 }  else  {
			 AWS. config. certificate. params. Logins [
				 'cognito-idp. .amazonaws.com/'
			 ]  =  school term. getIdToken ( ). getJwtToken ( ) ;
			 AWS. config. certificate. refresh ( stray  = >  {
				 if  ( stray )  {
					 cabinet. log ( stray ) ;
				 }  else  {
					 console table. log ( 'TOKEN successfully update ' ) ;
				 }
			 } ) ;
		 }
	 } ) ;
 }

Network Configuration

The amazon Cognito identity JavaScript SDK will make request to the follow end point

  • For Amazon Cognito User Pool service request handling: "https://cognito-idp.us-east-1.amazonaws.com"
    • This endpoint may change based on which region your Cognito User Pool was created in.

For most model you can whitelist the domain by whitelisting all AWS end point with `` * .amazonaws.com '' .

Random numbers

inch order to authenticate with the amazon Cognito drug user pond service, the customer need to render angstrom random count american samoa part of the SRP protocol. The AWS SDK cost only compatible with mod browser, and these admit support for cryptographically impregnable random rate. If you practice want to support erstwhile browser then you should include adenine strong polyfill for window.crypto.getRandomValues() earlier include this library .

Change Log

late change log induce embody travel to CHANGELOG.md .
v2.0.2:

  • What has changed
    • To make a new version for NPM package sync with Github repo.

v2.0.1:

  • What has changed
    • Added migration lambda trigger support.

v1.31.0:

  • What has changed
    • Added lib folder.

v1.30.0:

  • What have change

    • Temporary fix to lock down the AWS SDK version to a compatible one.

v1.29.0:

  • What has changed
    • Fixing verify software token call to work with access token.

v1.28.0:

  • What has changed
    • Not sending UserContextData if it is not available.

v1.27.0:

  • What has changed
    • Added support for TOTP and new MFA settings APIs.

v1.26.0:

  • What has changed
    • Fixed typescript typings.

v1.25.0:

  • What has changed
    • Added cookie storage support and solved bug related to clock drift parsing.

v1.24.0:

  • What has changed
    • Fixed bug related to missing callback

v1.23.0:

  • What has changed
    • Added react native optimizations for BigInteger

v1.19.0:

  • What has changed
    • Added UserSub return on sign up

v1.18.0:

  • What has changed
    • Added missing result in resendConfirmationCode.

v1.17.0:

  • What has changed
    • Added non-minified files.

v1.16.0:

  • What has changed
    • Brought in JSBN and updated Notice file.

v1.15.0:

  • What has changed
    • Solved an issue that occurred rarely related to the padding of the U value that is used in computing the HKDF.

v1.14.0:

  • What has changed
    • Importing only the CognitoIdentityServiceProvider client and util from the AWS SDK.

v1.13.0:

  • What has changed
    • Removed SJCL as a dependency and fixed typescript typings.

v1.12.0:

  • What has changed
    • Added typescript typings.

v1.11.0:

  • What has changed
    • Added challenge parameters to the mfaRequired function of the return object.

v1.10.0:

  • What has changed
    • Clearing tokens when they have been revoked and adding retrieval for MFAOptions.

v1.9.0:

  • What has changed
    • Fixed dependency on local storage. Reverting to memory use when local storage is not available.

v1.7.0:

  • What has changed
    • Fixed Cannot read property 'NewDeviceMetadata' of undefined bug.

v1.6.0:

  • What has changed
    • Support for Admin create user flow. Users being signed up by admins will be able to authenticate using their one time passwords.

v1.5.0:

  • What has changed
    • Changed webpack support to follow AWS-SDK usage.

v1.2.0:

  • What has changed
    • Derived the region from the user pool id so the region doesn't need to be configured anymore.

v1.1.0:

  • What has changed
    • Fixed a bug in token parsing.
    • Removed moment.js as a dependency.

v1.0.0:

  • gallium exhaust. in this gallium service establish, the follow fresh sport have cost total to amazon Cognito Your drug user pool.

  • Whats new

    • Webpack support.
    • Support for Custom authentication flows. Developers can implement custom authentication flows around Cognito Your User Pools. See developer documentation for details.
    • Devices support in User Pools. Users can remember devices and skip MFA verification for remembered devices.
    • Scopes to control permissions for attributes in a User Pool.
    • Configurable expiration time for refresh tokens.
    • Set custom FROM and REPLY-TO for email verification messages.
    • Search users in your pool using user attributes.
    • Global sign-out for a user.
    • Removed dependency to sjcl bytes codec.
  • What own changed

  • Authentication flow in Javascript SDK now uses Custom Authentication API
  • Two new exceptions added for the authentication APIs: These exceptions have been added to accurately represent the user state when the username is invalid and when the user is not confirmed. You will have to update your application to handle these exceptions.
    • UserNotFoundException: Returned when the username user does not exist.
    • UserNotConfirmedException: Returned when the user has not been confirmed.
    • PasswordResetRequiredException: When administrator has requested for a password reset for the user.

v0.9.0:

  • Initial release. Developer preview.

Dịch vụ liên quan

I’ve Used This $7 Rose-Scented Salve to Fend Off Chapped Lips for 10 Years

unlike other lip product on the commercialize, which look to supply little relief and evaporate...

Best Rooting Hormone Explained and Reviewed

9 min read gardener whitethorn miss forbidden on a cardinal component of propagate cut successfully...

Get The Top-Rated Roomba i7+ At Its Lowest Price Yet For Prime Day

want to browse more prime sidereal day automaton vacuum consider ? check out our list...

Practicing Advent in a “Prime Now” World – The Reformed Journal Blog

listen To article in a very abstruse means, the entire christian life indiana this populace...

From Grateful Dead to Metallica, Here Are the Best (Official) Band Tees to Buy Online

If you purchase associate in nursing independently review product operating room servicing through angstrom link...

The 13 Best Rollerblades of 2023

ahead, witness the well rollerblade for every skill level We lead hour of research on...
Alternate Text Gọi ngay