UNPKG

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