Search code examples
javascriptnode.jsamazon-cognitobun

How do I do Secure Remote Password (SRP) based sign in with Amazon Cognito in JavaScript?


I need to authenticate users against Amazon Cognito, and get JWTs. My Amazon Cognito User Pool Client uses the default Secure Remote Password (SRP) flow.

I have the username and password ready, how do I now actually use these to do the SRP calculations and sign in?

I know you can use AmplifyJS for this (and the amazon-cognito-identity-js NPM module that is now part of Amplify), but I'm curious for alternatives that may be more self-contained, and would work on the backend too--e.g. in integration tests we run in Node.js or Bun.


Solution

  • AWS released a Passwordless sample solution that (perhaps surprisingly) supports the SRP sign-in method out of the box as well. It works in the browser, as well as in Node.js and Bun:

    import { Passwordless } from "amazon-cognito-passwordless-auth";
    import { authenticateWithSRP } from "amazon-cognito-passwordless-auth/srp";
    
    Passwordless.configure({
      userPoolId: "<userPoolId>",
      clientId: "<clientId>",
      clientSecret: "<clientSecret>", // optional
    });
    
    authenticateWithSRP({
      username: "<username>",
      password: "<password>",
    }).signedIn.then((tokens) => {
      console.log(tokens);
    });
    

    Note that this is a solution created by an AWS prototyping team, not an official AWS SDK. See their repository here: https://github.com/aws-samples/amazon-cognito-passwordless-auth

    The SRP implementation, that is used under the hood by the code sample above, is largely contained in one source file––hopefully easy enough to glance through: https://github.com/aws-samples/amazon-cognito-passwordless-auth/blob/main/client/srp.ts

    Full disclosure: I'm one of the SA's that authored it.