UNPKG

34.4 kBMarkdownView Raw
1# Amazon Cognito Identity SDK for JavaScript
2
3You 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.
4
5We welcome developer feedback on this project. You can reach us by creating an issue on the
6GitHub repository or posting to the Amazon Cognito Identity forums and the below blog post:
7
8- https://github.com/aws-amplify/amplify-js
9- https://forums.aws.amazon.com/forum.jspa?forumID=173
10- https://aws.amazon.com/blogs/mobile/accessing-your-user-pools-using-the-amazon-cognito-identity-sdk-for-javascript/
11
12For an overview of the Cognito authentication flow, refer to the following blog post:
13
14- https://aws.amazon.com/blogs/mobile/customizing-your-user-pool-authentication-flow/
15
16# Introduction
17
18The 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.
19
20Your users will benefit from a number of security features including SMS-based Multi-Factor Authentication (MFA) and account verification via phone or email. The password features use the Secure Remote Password (SRP) protocol to avoid sending cleartext passwords over the wire.
21
22# Setup
23
24There are two ways to install the Amazon Cognito Identity SDK for JavaScript and its dependencies,
25depending on your project setup and experience with modern JavaScript build tools:
26
27- Download the bundle file from npm and include it in your HTML, or
28
29- Install the dependencies with npm and use a bundler like webpack.
30
31**Note:** This library uses the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). For [older browsers](https://caniuse.com/#feat=fetch) or in Node.js, you may need to include a polyfill. For example.
32
33```javascript
34global.fetch = require('node-fetch');
35var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
36```
37
38Note: We removed the build files in the github repo. You can use npm to download the whole package and extract the build files from it.
39
40## Install using separate JavaScript file
41
42This method is simpler and does not require additional tools, but may have worse performance due to
43the browser having to download multiple files.
44
45Download the amazon-cognito-identity-js package from npm and get `amazon-cognito-identity.min.js` file from the `dist` folder. Place it in your project.
46
47Optionally, to use other AWS services, include a build of the [AWS SDK for JavaScript](http://aws.amazon.com/sdk-for-browser/).
48
49Include all of the files in your HTML page before calling any Amazon Cognito Identity SDK APIs:
50
51```html
52<script src="/path/to/amazon-cognito-identity.min.js"></script>
53<!-- optional: only if you use other AWS services -->
54<script src="/path/to/aws-sdk-2.6.10.js"></script>
55```
56
57## Using NPM and Webpack
58
59Webpack is a popular JavaScript bundling and optimization tool, it has many configuration features that can build your
60source JavaScript into one or more files for distribution. The following is a quick setup guide with specific notes for
61using the Amazon Cognito Identity SDK for JavaScript with it, but there are many more ways it can be used, see
62[the Webpack site](https://webpack.github.io/), and in particular the
63[configuration documentation](http://webpack.github.io/docs/configuration.html)
64
65Note that webpack expects your source files to be structured as
66[CommonJS (Node.js-style) modules](https://webpack.github.io/docs/commonjs.html)
67(or [ECMAScript 2015 modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
68if you are using a transpiler such as [Babel](https://babeljs.io/).) If your project is not already using modules you
69may wish to use [Webpack's module shimming features](http://webpack.github.io/docs/shimming-modules.html) to ease
70migration.
71
72- Install [Node.js](https://nodejs.org) on your development machine (this will not be needed on your server.)
73
74- In your project add a `package.json`, either use `npm init` or the minimal:
75
76 ```json
77 {
78 "private": true
79 }
80 ```
81
82- Install the Amazon Cognito Identity SDK for JavaScript and the Webpack tool into your project with `npm` (the Node
83 Package Manager, which is installed with Node.js):
84
85 ```
86 > npm install --save-dev webpack json-loader
87 > npm install --save amazon-cognito-identity-js
88 ```
89
90 These will add a `node_modules` directory containing these tools and dependencies into your
91 project, you will probably want to exclude this directory from source control. Adding the `--save`
92 parameters will update the `package.json` file with instructions on what should be installed, so
93 you can simply call `npm install` without any parameters to recreate this folder later.
94
95- Create the configuration file for `webpack`, named `webpack.config.js`:
96
97 ```js
98 module.exports = {
99 // Example setup for your project:
100 // The entry module that requires or imports the rest of your project.
101 // Must start with `./`!
102 entry: './src/entry.js',
103 // Place output files in `./dist/my-app.js`
104 output: {
105 path: __dirname + '/dist',
106 filename: 'my-app.js',
107 },
108 module: {
109 rules: [
110 {
111 test: /\.json$/,
112 loader: 'json-loader',
113 },
114 ],
115 },
116 };
117 ```
118
119- Create the following directory where `webpack.config.js` resides, and create the entry file:
120
121 ```
122 > mkdir -p src
123 > touch src/entry.js
124 ```
125
126- Add the following into your `package.json`
127
128 ```json
129 {
130 "scripts": {
131 "build": "webpack"
132 }
133 }
134 ```
135
136- Build your application bundle with `npm run build`
137
138## Install for React Native
139
140See [Using NPM and Webpack](https://github.com/aws/amazon-cognito-identity-js#using-npm-and-webpack) for more information on NPM.
141
142- Install and add to your dependencies the Amazon Cognito Identity SDK for JavaScript:
143
144```
145npm install --save amazon-cognito-identity-js
146```
147
148- Install react-native-cli if you have not already:
149
150```
151npm install -g react-native-cli
152```
153
154- Link the native modules to your project:
155
156```
157react-native link amazon-cognito-identity-js
158```
159
160## Configuration
161
162The Amazon Cognito Identity SDK for JavaScript requires two configuration values from your AWS
163Account in order to access your Cognito User Pool:
164
165- The User Pool Id, e.g. `us-east-1_aB12cDe34`
166- A User Pool App Client Id, e.g. `7ghr5379orhbo88d52vphda6s9`
167 - When creating the App, the generate client secret box must be **unchecked** because the
168 JavaScript SDK doesn't support apps that have a client secret.
169
170The [AWS Console for Cognito User Pools](https://console.aws.amazon.com/cognito/users/) can be used to get or create these values.
171
172If you will be using Cognito Federated Identity to provide access to your AWS resources or Cognito Sync you will also need the Id of a Cognito Identity Pool that will accept logins from the above Cognito User Pool and App, i.e. `us-east-1:85156295-afa8-482c-8933-1371f8b3b145`.
173
174Note that the various errors returned by the service are valid JSON so one can access the different exception types (err.code) and status codes (err.statusCode).
175
176## Relevant examples
177
178For an example using babel-webpack of a React setup, see [babel-webpack example](https://github.com/aws/amazon-cognito-identity-js/tree/master/examples/babel-webpack).
179
180For a working example using angular, see [cognito-angular2-quickstart](https://github.com/awslabs/aws-cognito-angular2-quickstart).
181
182For a working example using ember.js, see:
183
184- [aws-serverless-ember](https://github.com/awslabs/aws-serverless-ember).
185- [aws-mobilehub-ember](https://github.com/awslabs/aws-mobilehub-ember).
186
187If you are having issues when using Aurelia, please see the following [Stack Overflow post](http://stackoverflow.com/questions/39714424/how-can-i-get-the-amazon-cognito-identity-sdk-working-in-aurelia).
188
189## Usage
190
191The usage examples below use the unqualified names for types in the Amazon Cognito Identity SDK for JavaScript. Remember to import or qualify access to any of these types:
192
193```javascript
194// When using loose Javascript files:
195var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
196
197// Modules, e.g. Webpack:
198var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
199var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
200
201// ES Modules, e.g. transpiling with Babel
202import {
203 CognitoUserPool,
204 CognitoUserAttribute,
205 CognitoUser,
206} from 'amazon-cognito-identity-js';
207```
208
209**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.
210
211```javascript
212var poolData = {
213 UserPoolId: '...', // Your user pool id here
214 ClientId: '...', // Your client id here
215};
216var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
217
218var attributeList = [];
219
220var dataEmail = {
221 Name: 'email',
222 Value: 'email@mydomain.com',
223};
224
225var dataPhoneNumber = {
226 Name: 'phone_number',
227 Value: '+15555555555',
228};
229var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
230var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute(
231 dataPhoneNumber
232);
233
234attributeList.push(attributeEmail);
235attributeList.push(attributePhoneNumber);
236
237userPool.signUp('username', 'password', attributeList, null, function(
238 err,
239 result
240) {
241 if (err) {
242 alert(err.message || JSON.stringify(err));
243 return;
244 }
245 var cognitoUser = result.user;
246 console.log('user name is ' + cognitoUser.getUsername());
247});
248```
249
250**Use case 2.** Confirming a registered, unauthenticated user using a confirmation code received via SMS.
251
252```javascript
253var poolData = {
254 UserPoolId: '...', // Your user pool id here
255 ClientId: '...', // Your client id here
256};
257
258var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
259var userData = {
260 Username: 'username',
261 Pool: userPool,
262};
263
264var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
265cognitoUser.confirmRegistration('123456', true, function(err, result) {
266 if (err) {
267 alert(err.message || JSON.stringify(err));
268 return;
269 }
270 console.log('call result: ' + result);
271});
272```
273
274**Use case 3.** Resending a confirmation code via SMS for confirming registration for a unauthenticated user.
275
276```javascript
277cognitoUser.resendConfirmationCode(function(err, result) {
278 if (err) {
279 alert(err.message || JSON.stringify(err));
280 return;
281 }
282 console.log('call result: ' + result);
283});
284```
285
286**Use case 4.** Authenticating a user and establishing a user session with the Amazon Cognito Identity service.
287
288```javascript
289import * as AWS from 'aws-sdk/global';
290
291var authenticationData = {
292 Username: 'username',
293 Password: 'password',
294};
295var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
296 authenticationData
297);
298var poolData = {
299 UserPoolId: '...', // Your user pool id here
300 ClientId: '...', // Your client id here
301};
302var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
303var userData = {
304 Username: 'username',
305 Pool: userPool,
306};
307var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
308cognitoUser.authenticateUser(authenticationDetails, {
309 onSuccess: function(result) {
310 var accessToken = result.getAccessToken().getJwtToken();
311
312 //POTENTIAL: Region needs to be set if not already set previously elsewhere.
313 AWS.config.region = '<region>';
314
315 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
316 IdentityPoolId: '...', // your identity pool id here
317 Logins: {
318 // Change the key below according to the specific region your user pool is in.
319 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result
320 .getIdToken()
321 .getJwtToken(),
322 },
323 });
324
325 //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
326 AWS.config.credentials.refresh(error => {
327 if (error) {
328 console.error(error);
329 } else {
330 // Instantiate aws sdk service objects now that the credentials have been updated.
331 // example: var s3 = new AWS.S3();
332 console.log('Successfully logged!');
333 }
334 });
335 },
336
337 onFailure: function(err) {
338 alert(err.message || JSON.stringify(err));
339 },
340});
341```
342
343Note that if device tracking is enabled for the user pool with a setting that user opt-in is required, you need to implement an onSuccess(result, userConfirmationNecessary) callback, collect user input and call either setDeviceStatusRemembered to remember the device or setDeviceStatusNotRemembered to not remember the device.
344
345Note also that if CognitoUser.authenticateUser throws ReferenceError: navigator is not defined when running on Node.js, follow the instructions on the following [Stack Overflow post](http://stackoverflow.com/questions/40219518/aws-cognito-unauthenticated-login-error-window-is-not-defined-js).
346
347**Use case 5.** Retrieve user attributes for an authenticated user.
348
349```javascript
350cognitoUser.getUserAttributes(function(err, result) {
351 if (err) {
352 alert(err.message || JSON.stringify(err));
353 return;
354 }
355 for (i = 0; i < result.length; i++) {
356 console.log(
357 'attribute ' + result[i].getName() + ' has value ' + result[i].getValue()
358 );
359 }
360});
361```
362
363**Use case 6.** Verify user attribute for an authenticated user.
364
365Note that the inputVerificationCode method needs to be defined but does not need to actually do anything. If you would like the user to input the verification code on another page, you can set inputVerificationCode to null. If inputVerificationCode is null, onSuccess will be called immediately (assuming there is no error).
366
367```javascript
368cognitoUser.getAttributeVerificationCode('email', {
369 onSuccess: function(result) {
370 console.log('call result: ' + result);
371 },
372 onFailure: function(err) {
373 alert(err.message || JSON.stringify(err));
374 },
375 inputVerificationCode: function() {
376 var verificationCode = prompt('Please input verification code: ', '');
377 cognitoUser.verifyAttribute('email', verificationCode, this);
378 },
379});
380```
381
382**Use case 7.** Delete user attribute for an authenticated user.
383
384```javascript
385var attributeList = [];
386attributeList.push('nickname');
387
388cognitoUser.deleteAttributes(attributeList, function(err, result) {
389 if (err) {
390 alert(err.message || JSON.stringify(err));
391 return;
392 }
393 console.log('call result: ' + result);
394});
395```
396
397**Use case 8.** Update user attributes for an authenticated user.
398
399```javascript
400var attributeList = [];
401var attribute = {
402 Name: 'nickname',
403 Value: 'joe',
404};
405var attribute = new AmazonCognitoIdentity.CognitoUserAttribute(attribute);
406attributeList.push(attribute);
407
408cognitoUser.updateAttributes(attributeList, function(err, result) {
409 if (err) {
410 alert(err.message || JSON.stringify(err));
411 return;
412 }
413 console.log('call result: ' + result);
414});
415```
416
417**Use case 9.** Enabling MFA for a user on a pool that has an optional MFA setting for an authenticated user.
418
419Note: this method is now deprecated. Please use `setUserMfaPreference` instead.
420
421```javascript
422cognitoUser.enableMFA(function(err, result) {
423 if (err) {
424 alert(err.message || JSON.stringify(err));
425 return;
426 }
427 console.log('call result: ' + result);
428});
429```
430
431**Use case 10.** Disabling MFA for a user on a pool that has an optional MFA setting for an authenticated user.
432
433Note: this method is now deprecated. Please use `setUserMfaPreference` instead.
434
435```javascript
436cognitoUser.disableMFA(function(err, result) {
437 if (err) {
438 alert(err.message || JSON.stringify(err));
439 return;
440 }
441 console.log('call result: ' + result);
442});
443```
444
445**Use case 11.** Changing the current password for an authenticated user.
446
447```javascript
448cognitoUser.changePassword('oldPassword', 'newPassword', function(err, result) {
449 if (err) {
450 alert(err.message || JSON.stringify(err));
451 return;
452 }
453 console.log('call result: ' + result);
454});
455```
456
457**Use case 12.** Starting and completing a forgot password flow for an unauthenticated user.
458
459For example:
460
461```html
462<body>
463 <label for="#code">Code: </label>
464 <input id="code"></input>
465 </br>
466 <label for="#new_password">New Password: </label>
467 <input id="new_password" type="password"></input>
468 <br/>
469</body>
470```
471
472```javascript
473cognitoUser.forgotPassword({
474 onSuccess: function(data) {
475 // successfully initiated reset password request
476 console.log('CodeDeliveryData from forgotPassword: ' + data);
477 },
478 onFailure: function(err) {
479 alert(err.message || JSON.stringify(err));
480 },
481 //Optional automatic callback
482 inputVerificationCode: function(data) {
483 console.log('Code sent to: ' + data);
484 var code = document.getElementById('code').value;
485 var newPassword = document.getElementById('new_password').value;
486 cognitoUser.confirmPassword(verificationCode, newPassword, {
487 onSuccess() {
488 console.log('Password confirmed!');
489 },
490 onFailure(err) {
491 console.log('Password not confirmed!');
492 },
493 });
494 },
495});
496```
497
498**Use case 13.** Deleting an authenticated user.
499
500```javascript
501cognitoUser.deleteUser(function(err, result) {
502 if (err) {
503 alert(err.message || JSON.stringify(err));
504 return;
505 }
506 console.log('call result: ' + result);
507});
508```
509
510**Use case 14.** Signing out from the application.
511
512```javascript
513cognitoUser.signOut();
514```
515
516**Use case 15.** Global signout for an authenticated user(invalidates all issued tokens).
517
518```javascript
519cognitoUser.globalSignOut(callback);
520```
521
522**Use case 16 with React Native.**
523
524In React Native, loading the persisted current user information requires an extra async call to be made:
525
526```javascript
527var poolData = {
528 UserPoolId: '...', // Your user pool id here
529 ClientId: '...', // Your client id here
530};
531var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
532
533userPool.storage.sync(function(err, result) {
534 if (err) {
535 } else if (result === 'SUCCESS') {
536 var cognitoUser = userPool.getCurrentUser();
537 // Continue with steps in Use case 16
538 }
539});
540```
541
542**Use case 16.** Retrieving the current user from local storage.
543
544```javascript
545var poolData = {
546 UserPoolId: '...', // Your user pool id here
547 ClientId: '...', // Your client id here
548};
549var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
550var cognitoUser = userPool.getCurrentUser();
551
552if (cognitoUser != null) {
553 cognitoUser.getSession(function(err, session) {
554 if (err) {
555 alert(err.message || JSON.stringify(err));
556 return;
557 }
558 console.log('session validity: ' + session.isValid());
559
560 // NOTE: getSession must be called to authenticate user before calling getUserAttributes
561 cognitoUser.getUserAttributes(function(err, attributes) {
562 if (err) {
563 // Handle error
564 } else {
565 // Do something with attributes
566 }
567 });
568
569 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
570 IdentityPoolId: '...', // your identity pool id here
571 Logins: {
572 // Change the key below according to the specific region your user pool is in.
573 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': session
574 .getIdToken()
575 .getJwtToken(),
576 },
577 });
578
579 // Instantiate aws sdk service objects now that the credentials have been updated.
580 // example: var s3 = new AWS.S3();
581 });
582}
583```
584
585**Use case 17.** Integrating User Pools with Cognito Identity.
586
587```javascript
588var cognitoUser = userPool.getCurrentUser();
589
590if (cognitoUser != null) {
591 cognitoUser.getSession(function(err, result) {
592 if (result) {
593 console.log('You are now logged in.');
594
595 //POTENTIAL: Region needs to be set if not already set previously elsewhere.
596 AWS.config.region = '<region>';
597
598 // Add the User's Id Token to the Cognito credentials login map.
599 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
600 IdentityPoolId: 'YOUR_IDENTITY_POOL_ID',
601 Logins: {
602 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result
603 .getIdToken()
604 .getJwtToken(),
605 },
606 });
607 }
608 });
609}
610//call refresh method in order to authenticate user and get new temp credentials
611AWS.config.credentials.refresh(error => {
612 if (error) {
613 console.error(error);
614 } else {
615 console.log('Successfully logged!');
616 }
617});
618```
619
620_note that you can not replace the login key with a variable because it will be interpreted literally. if you want to use a variable, the resolution to [issue 17](https://github.com/aws/amazon-cognito-identity-js/issues/162) has a working example_
621
622**Use case 18.** List all remembered devices for an authenticated user. In this case, we need to pass a limit on the number of devices retrieved at a time and a pagination token is returned to make subsequent calls. The pagination token can be subsequently passed. When making the first call, the pagination token should be null.
623
624```javascript
625cognitoUser.listDevices(limit, paginationToken, {
626 onSuccess: function(result) {
627 console.log('call result: ' + result);
628 },
629 onFailure: function(err) {
630 alert(err.message);
631 },
632});
633```
634
635**Use case 19.** List information about the current device.
636
637```javascript
638cognitoUser.getDevice({
639 onSuccess: function(result) {
640 console.log('call result: ' + result);
641 },
642 onFailure: function(err) {
643 alert(err.message || JSON.stringify(err));
644 },
645});
646```
647
648**Use case 20.** Remember a device.
649
650```javascript
651cognitoUser.setDeviceStatusRemembered({
652 onSuccess: function(result) {
653 console.log('call result: ' + result);
654 },
655 onFailure: function(err) {
656 alert(err.message || JSON.stringify(err));
657 },
658});
659```
660
661**Use case 21.** Do not remember a device.
662
663```javascript
664cognitoUser.setDeviceStatusNotRemembered({
665 onSuccess: function(result) {
666 console.log('call result: ' + result);
667 },
668 onFailure: function(err) {
669 alert(err.message || JSON.stringify(err));
670 },
671});
672```
673
674**Use case 22.** Forget the current device.
675
676```javascript
677cognitoUser.forgetDevice({
678 onSuccess: function(result) {
679 console.log('call result: ' + result);
680 },
681 onFailure: function(err) {
682 alert(err.message || JSON.stringify(err));
683 },
684});
685```
686
687**Use case 23.** Authenticate a user and set new password for a user that was created using AdminCreateUser API.
688
689```javascript
690
691 var cognitoUser, sessionUserAttributes; // global variables to handle completeNewPasswordChallenge flow
692
693 // ...
694
695 cognitoUser.authenticateUser(authenticationDetails, {
696 onSuccess: function (result) {
697 // User authentication was successful
698 },
699
700 onFailure: function(err) {
701 // User authentication was not successful
702 },
703
704 mfaRequired: function(codeDeliveryDetails) {
705 // MFA is required to complete user authentication.
706 // Get the code from user and call
707 cognitoUser.sendMFACode(mfaCode, this)
708 },
709
710 newPasswordRequired: function(userAttributes, requiredAttributes) {
711 // User was signed up by an admin and must provide new
712 // password and required attributes, if any, to complete
713 // authentication.
714
715 // the api doesn't accept this field back
716 delete userAttributes.email_verified;
717
718 // store userAttributes on global variable
719 sessionUserAttributes = userAttributes;
720 }
721 });
722
723 // ... handle new password flow on your app
724 handleNewPassword(newPassword) {
725 cognitoUser.completeNewPasswordChallenge(newPassword, sessionUserAttributes);
726 }
727
728```
729
730**Use case 24.** Retrieve the MFA Options for the user in case MFA is optional.
731
732```javascript
733cognitoUser.getMFAOptions(function(err, mfaOptions) {
734 if (err) {
735 alert(err.message || JSON.stringify(err));
736 return;
737 }
738 console.log('MFA options for user ' + mfaOptions);
739});
740```
741
742**Use case 25.** Authenticating a user with a passwordless custom flow.
743
744```javascript
745cognitoUser.setAuthenticationFlowType('CUSTOM_AUTH');
746
747cognitoUser.initiateAuth(authenticationDetails, {
748 onSuccess: function(result) {
749 // User authentication was successful
750 },
751 onFailure: function(err) {
752 // User authentication was not successful
753 },
754 customChallenge: function(challengeParameters) {
755 // User authentication depends on challenge response
756 var challengeResponses = 'challenge-answer';
757 cognitoUser.sendCustomChallengeAnswer(challengeResponses, this);
758 },
759});
760```
761
762**Use case 26.** Using cookies to store cognito tokens
763
764```javascript
765```
766
767To use the CookieStorage you have to pass it in the constructor map of CognitoUserPool and CognitoUser (when constructed directly):
768
769```js
770 var poolData = {
771 UserPoolId : '...', // Your user pool id here
772 ClientId : '...' // Your client id here
773 Storage: new AmazonCognitoIdentity.CookieStorage({domain: ".yourdomain.com"})
774 };
775
776 var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
777
778 var userData = {
779 Username: 'username',
780 Pool: userPool,
781 Storage: new AmazonCognitoIdentity.CookieStorage({domain: ".yourdomain.com"})
782 };
783```
784
785The CookieStorage object receives a map (data) in its constructor that may have these values:
786
787- data.domain Cookies domain (mandatory)
788- data.path Cookies path (default: '/')
789- data.expires Cookie expiration (in days, default: 365)
790- data.secure Cookie secure flag (default: true)
791
792**Use case 27.** Selecting the MFA method and authenticating using TOTP.
793
794```js
795var authenticationData = {
796 Username: 'username',
797 Password: 'password',
798};
799var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
800 authenticationData
801);
802var poolData = {
803 UserPoolId: '...', // Your user pool id here
804 ClientId: '...', // Your client id here
805};
806var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
807var userData = {
808 Username: 'username',
809 Pool: userPool,
810};
811var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
812
813cognitoUser.authenticateUser(authenticationDetails, {
814 onSuccess: function(result) {
815 var accessToken = result.getAccessToken().getJwtToken();
816 },
817
818 onFailure: function(err) {
819 alert(err.message || JSON.stringify(err));
820 },
821
822 mfaSetup: function(challengeName, challengeParameters) {
823 cognitoUser.associateSoftwareToken(this);
824 },
825
826 associateSecretCode: function(secretCode) {
827 var challengeAnswer = prompt('Please input the TOTP code.', '');
828 cognitoUser.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
829 },
830
831 selectMFAType: function(challengeName, challengeParameters) {
832 var mfaType = prompt('Please select the MFA method.', ''); // valid values for mfaType is "SMS_MFA", "SOFTWARE_TOKEN_MFA"
833 cognitoUser.sendMFASelectionAnswer(mfaType, this);
834 },
835
836 totpRequired: function(secretCode) {
837 var challengeAnswer = prompt('Please input the TOTP code.', '');
838 cognitoUser.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
839 },
840
841 mfaRequired: function(codeDeliveryDetails) {
842 var verificationCode = prompt('Please input verification code', '');
843 cognitoUser.sendMFACode(verificationCode, this);
844 },
845});
846```
847
848**Use case 28.** Enabling and setting SMS MFA as the preferred MFA method for the user.
849
850```js
851smsMfaSettings = {
852 PreferredMfa: true,
853 Enabled: true,
854};
855cognitoUser.setUserMfaPreference(smsMfaSettings, null, function(err, result) {
856 if (err) {
857 alert(err.message || JSON.stringify(err));
858 }
859 console.log('call result ' + result);
860});
861```
862
863**Use case 29.** Enabling and setting TOTP MFA as the preferred MFA method for the user.
864
865```js
866totpMfaSettings = {
867 PreferredMfa: true,
868 Enabled: true,
869};
870cognitoUser.setUserMfaPreference(null, totpMfaSettings, function(err, result) {
871 if (err) {
872 alert(err.message || JSON.stringify(err));
873 }
874 console.log('call result ' + result);
875});
876```
877
878**Use case 30.** Authenticating a user with a user password auth flow.
879
880```js
881cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');
882
883cognitoUser.authenticateUser(authenticationDetails, {
884 onSuccess: function(result) {
885 // User authentication was successful
886 },
887 onFailure: function(err) {
888 // User authentication was not successful
889 },
890 mfaRequired: function(codeDeliveryDetails) {
891 // MFA is required to complete user authentication.
892 // Get the code from user and call
893 cognitoUser.sendMFACode(verificationCode, this);
894 },
895});
896```
897
898**Use case 31.** Retrieve the user data for an authenticated user.
899
900```js
901cognitoUser.getUserData(function(err, userData) {
902 if (err) {
903 alert(err.message || JSON.stringify(err));
904 return;
905 }
906 console.log('User data for user ' + userData);
907});
908
909// If you want to force to get the user data from backend,
910// you can set the bypassCache to true
911cognitoUser.getUserData(
912 function(err, userData) {
913 if (err) {
914 alert(err.message || JSON.stringify(err));
915 return;
916 }
917 console.log('User data for user ' + userData);
918 },
919 { bypassCache: true }
920);
921```
922
923**Use case 32.** Handling expiration of the Id Token.
924
925```js
926refresh_token = session.getRefreshToken(); // receive session from calling cognitoUser.getSession()
927if (AWS.config.credentials.needsRefresh()) {
928 cognitoUser.refreshSession(refresh_token, (err, session) => {
929 if (err) {
930 console.log(err);
931 } else {
932 AWS.config.credentials.params.Logins[
933 'cognito-idp.<YOUR-REGION>.amazonaws.com/<YOUR_USER_POOL_ID>'
934 ] = session.getIdToken().getJwtToken();
935 AWS.config.credentials.refresh(err => {
936 if (err) {
937 console.log(err);
938 } else {
939 console.log('TOKEN SUCCESSFULLY UPDATED');
940 }
941 });
942 }
943 });
944}
945```
946
947## Network Configuration
948
949The Amazon Cognito Identity JavaScript SDK will make requests to the following endpoints
950
951- For Amazon Cognito User Pool service request handling: "https://cognito-idp.us-east-1.amazonaws.com"
952 - This endpoint may change based on which region your Cognito User Pool was created in.
953
954For most frameworks you can whitelist the domain by whitelisting all AWS endpoints with "\*.amazonaws.com".
955
956## Random numbers
957
958In order to authenticate with the Amazon Cognito User Pool Service, the client needs to generate a random number as part of the SRP protocol. The AWS SDK is only compatible with modern browsers, and these include [support for cryptographically strong random values](https://caniuse.com/#feat=cryptography). If you do need to support older browsers then you should include a strong polyfill for `window.crypto.getRandomValues()` before including this library.
959
960## Change Log
961
962Latest change logs have been moved to [CHANGELOG.md](./CHANGELOG.md).
963
964**v2.0.2:**
965
966- What has changed
967 - To make a new version for NPM package sync with Github repo.
968
969**v2.0.1:**
970
971- What has changed
972 - Added migration lambda trigger support.
973
974**v1.31.0:**
975
976- What has changed
977 - Added lib folder.
978
979**v1.30.0:**
980
981- What has changed
982
983 - Temporary fix to lock down the AWS SDK version to a compatible one.
984
985**v1.29.0:**
986
987- What has changed
988 - Fixing verify software token call to work with access token.
989
990**v1.28.0:**
991
992- What has changed
993 - Not sending UserContextData if it is not available.
994
995**v1.27.0:**
996
997- What has changed
998 - Added support for TOTP and new MFA settings APIs.
999
1000**v1.26.0:**
1001
1002- What has changed
1003 - Fixed typescript typings.
1004
1005**v1.25.0:**
1006
1007- What has changed
1008 - Added cookie storage support and solved bug related to clock drift parsing.
1009
1010**v1.24.0:**
1011
1012- What has changed
1013 - Fixed bug related to missing callback
1014
1015**v1.23.0:**
1016
1017- What has changed
1018 - Added react native optimizations for BigInteger
1019
1020**v1.19.0:**
1021
1022- What has changed
1023 - Added UserSub return on sign up
1024
1025**v1.18.0:**
1026
1027- What has changed
1028 - Added missing result in resendConfirmationCode.
1029
1030**v1.17.0:**
1031
1032- What has changed
1033 - Added non-minified files.
1034
1035**v1.16.0:**
1036
1037- What has changed
1038 - Brought in JSBN and updated Notice file.
1039
1040**v1.15.0:**
1041
1042- What has changed
1043 - Solved an issue that occurred rarely related to the padding of the U value that is used in computing the HKDF.
1044
1045**v1.14.0:**
1046
1047- What has changed
1048 - Importing only the CognitoIdentityServiceProvider client and util from the AWS SDK.
1049
1050**v1.13.0:**
1051
1052- What has changed
1053 - Removed SJCL as a dependency and fixed typescript typings.
1054
1055**v1.12.0:**
1056
1057- What has changed
1058 - Added typescript typings.
1059
1060**v1.11.0:**
1061
1062- What has changed
1063 - Added challenge parameters to the mfaRequired function of the return object.
1064
1065**v1.10.0:**
1066
1067- What has changed
1068 - Clearing tokens when they have been revoked and adding retrieval for MFAOptions.
1069
1070**v1.9.0:**
1071
1072- What has changed
1073 - Fixed dependency on local storage. Reverting to memory use when local storage is not available.
1074
1075**v1.7.0:**
1076
1077- What has changed
1078 - Fixed Cannot read property 'NewDeviceMetadata' of undefined bug.
1079
1080**v1.6.0:**
1081
1082- What has changed
1083 - Support for Admin create user flow. Users being signed up by admins will be able to authenticate using their one time passwords.
1084
1085**v1.5.0:**
1086
1087- What has changed
1088 - Changed webpack support to follow AWS-SDK usage.
1089
1090**v1.2.0:**
1091
1092- What has changed
1093 - Derived the region from the user pool id so the region doesn't need to be configured anymore.
1094
1095**v1.1.0:**
1096
1097- What has changed
1098 - Fixed a bug in token parsing.
1099 - Removed moment.js as a dependency.
1100
1101**v1.0.0:**
1102
1103- GA release. In this GA service launch, the following new features have been added to Amazon Cognito Your User Pools.
1104
1105- Whats new
1106
1107 - Webpack support.
1108 - Support for Custom authentication flows. Developers can implement custom authentication flows around Cognito Your User Pools. See developer documentation for details.
1109 - Devices support in User Pools. Users can remember devices and skip MFA verification for remembered devices.
1110 - Scopes to control permissions for attributes in a User Pool.
1111 - Configurable expiration time for refresh tokens.
1112 - Set custom FROM and REPLY-TO for email verification messages.
1113 - Search users in your pool using user attributes.
1114 - Global sign-out for a user.
1115 - Removed dependency to sjcl bytes codec.
1116
1117- What has changed
1118 - Authentication flow in Javascript SDK now uses Custom Authentication API
1119 - 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.
1120 - UserNotFoundException: Returned when the username user does not exist.
1121 - UserNotConfirmedException: Returned when the user has not been confirmed.
1122 - PasswordResetRequiredException: When administrator has requested for a password reset for the user.
1123
1124**v0.9.0:**
1125
1126- Initial release. Developer preview.