0
0
AwsHow-ToBeginner · 4 min read

How to Use AWS Cognito for Authentication: Simple Guide

Use AWS Cognito User Pools to manage user sign-up and sign-in securely. Integrate Cognito SDK in your app to authenticate users by calling signUp and signIn methods, which handle user credentials and tokens automatically.
📐

Syntax

To use AWS Cognito for authentication, you typically interact with the CognitoUserPool and CognitoUser classes from the AWS Amplify or AWS SDK. The main steps are:

  • Create a User Pool in AWS Cognito console.
  • Use signUp to register users.
  • Use signIn to authenticate users.
  • Use tokens returned to manage sessions.

Each method requires user credentials like username and password.

javascript
const poolData = {
  UserPoolId: 'us-east-1_example', // Your user pool id here
  ClientId: 'exampleclientid123456789' // Your app client id here
};

const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

// Sign up syntax
userPool.signUp(username, password, attributeList, null, function(err, result) {
  if (err) {
    console.error(err.message || JSON.stringify(err));
    return;
  }
  const cognitoUser = result.user;
  console.log('User name is ' + cognitoUser.getUsername());
});

// Sign in syntax
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
  Username: username,
  Password: password
});

const userData = {
  Username: username,
  Pool: userPool
};

const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    console.log('Access token: ' + result.getAccessToken().getJwtToken());
  },
  onFailure: function(err) {
    console.error(err.message || JSON.stringify(err));
  }
});
💻

Example

This example shows how to sign up a new user and then sign in using AWS Cognito with the AWS Cognito Identity SDK for JavaScript.

javascript
import { CognitoUserPool, CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js';

const poolData = {
  UserPoolId: 'us-east-1_123456789',
  ClientId: '1h2g3f4e5d6c7b8a9i0jklmnop'
};

const userPool = new CognitoUserPool(poolData);

// Sign up a user
function signUpUser(username, password, email) {
  const attributeList = [
    {
      Name: 'email',
      Value: email
    }
  ];

  userPool.signUp(username, password, attributeList, null, (err, result) => {
    if (err) {
      console.error('Error during sign up:', err.message || JSON.stringify(err));
      return;
    }
    console.log('User signed up:', result.user.getUsername());
  });
}

// Sign in a user
function signInUser(username, password) {
  const authenticationDetails = new AuthenticationDetails({
    Username: username,
    Password: password
  });

  const userData = {
    Username: username,
    Pool: userPool
  };

  const cognitoUser = new CognitoUser(userData);

  cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: (result) => {
      console.log('Access token:', result.getAccessToken().getJwtToken());
    },
    onFailure: (err) => {
      console.error('Authentication failed:', err.message || JSON.stringify(err));
    }
  });
}

// Usage example
signUpUser('testuser', 'TestPass123!', 'testuser@example.com');
signInUser('testuser', 'TestPass123!');
Output
User signed up: testuser Access token: eyJraWQiOiJLT0... (JWT token string)
⚠️

Common Pitfalls

Common mistakes when using Cognito for authentication include:

  • Not confirming the user after sign-up (users must be confirmed to sign in).
  • Using wrong UserPoolId or ClientId.
  • Ignoring password policy errors (Cognito enforces strong passwords).
  • Not handling asynchronous callbacks properly.
  • Forgetting to handle multi-factor authentication if enabled.

Always check error messages carefully and confirm users if needed.

javascript
/* Wrong: Trying to sign in before user confirmation */
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: (result) => {
    console.log('Signed in');
  },
  onFailure: (err) => {
    console.error('Error:', err.message);
  }
});

/* Right: Confirm user first, then sign in */
userPool.confirmRegistration(username, confirmationCode, true, (err, result) => {
  if (err) {
    console.error('Confirmation error:', err.message);
    return;
  }
  console.log('User confirmed:', result);
  // Now sign in
  cognitoUser.authenticateUser(authenticationDetails, { /* ... */ });
});
📊

Quick Reference

Remember these key points when using AWS Cognito for authentication:

  • User Pool: Central place to manage users.
  • Sign Up: Registers new users with attributes.
  • Confirm User: Required if auto-confirm is off.
  • Sign In: Authenticates users and returns tokens.
  • Tokens: Use JWT tokens for session management.

Key Takeaways

Create and configure a Cognito User Pool to manage users securely.
Use signUp and signIn methods from AWS SDK to register and authenticate users.
Always confirm users if your pool requires it before allowing sign-in.
Handle errors and password policies carefully to avoid common issues.
Use the JWT tokens returned on sign-in to manage user sessions in your app.