|

|  How to Access Amazon Cognito API for User Authentication in JavaScript

How to Access Amazon Cognito API for User Authentication in JavaScript

October 31, 2024

Learn to access Amazon Cognito API for user authentication using JavaScript. Follow our step-by-step guide to integrate secure login into your app efficiently.

How to Access Amazon Cognito API for User Authentication in JavaScript

 

Set Up Amazon Cognito User Pool

 

  • Before you start coding, ensure that you have an Amazon Cognito User Pool set up. A User Pool is a user directory that helps manage sign-up and sign-in functionalities for your applications.
  • Note the User Pool ID and App Client ID as you'll need these in your application. Ensure app clients are configured to allow API operations without a secret for JavaScript applications.

 

Install AWS SDK for JavaScript

 

  • To interact with the Amazon Cognito API using JavaScript, you need to have the AWS SDK for JavaScript installed. You can include it in your project using npm or a Content Delivery Network (CDN).
  •  

  • Using npm:
npm install aws-sdk
  • Using a CDN:
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.814.0.min.js"></script>

 

Configure AWS Cognito Credentials

 

  • To access Amazon Cognito services, you need to configure the AWS SDK with the User Pool ID and App Client ID. This is often done by creating an instance of `CognitoUserPool`.
const poolData = {
  UserPoolId: 'your_user_pool_id', // Your user pool ID
  ClientId: 'your_app_client_id'    // Your app client ID
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

 

Authenticate a User

 

  • To log in a user, you'll use `authenticateUser`. You'll need to collect the username and password from the user, and initiate the authentication using Cognito.
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
  Username: 'username_here',
  Password: 'password_here'
});

const userData = {
  Username: 'username_here',
  Pool: userPool
};

const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    console.log('Access token + ' + result.getAccessToken().getJwtToken());
  },
  onFailure: function (err) {
    alert(err.message || JSON.stringify(err));
  }
});

 

Implement Token Handling

 

  • Upon successful authentication, Cognito returns tokens (id token, access token, and refresh token) that you can use to access AWS resources.
  • Securely store these tokens, usually in a session or local storage, and handle refresh tokens to maintain a user's session without forcing them to log in repeatedly.

 

Integrate with Protected API

 

  • Once authenticated, you can use the access token to make authorized requests to your server or protected AWS resources.
  • Include the access token in the request headers to authenticate with the protected API.
fetch('https://yourapi.com/endpoint', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer ' + accessToken
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => console.error('Error:', error));

 

Handle Sign-Up and Verification

 

  • To include a sign-up feature, you can use the `signUp` method. Ensure you handle email/phone verification depending on how your Cognito User Pool is configured.
  • For account verification, implement `confirmRegistration` with a confirmation code sent to the user's email or phone.
userPool.signUp('username_here', 'password_here', [], null, (err, result) => {
  if (err) {
    alert(err.message || JSON.stringify(err));
    return;
  }
  cognitoUser = result.user;
  console.log('user name is ' + cognitoUser.getUsername());
});
cognitoUser.confirmRegistration('confirmation_code_here', true, function(err, result) {
  if (err) {
    alert(err.message || JSON.stringify(err));
    return;
  }
  console.log('call result: ' + result);
});