50

I'm just now diving into Cognito. The AWS setup has been fairly straight-forward, easy.

We have a variety of apps, webapps, and services and we'd like those to make use of the Cognito service. I've experience setting up similar with Auth0, but because we've been leveraging a number of Amazon Web Services, it really makes sense to use Cognito as well.

Everywhere I look, every guide eventually references Amplify client-side library and cli. We have existing apps and services, and really don't want to change tooling or import anything unnecessary to add bloat and complexity. Is there a way to use Cognito service without Amplify libraries? Is there a lightweight Cognito-only client library for interfacing with the Cognito service, authentication-and-authorization flow?

Michael Prescott
  • 764
  • 1
  • 6
  • 14
  • 1
    Did you manage to use Cognito without Amplify? I also want to use just Cognito and no other services. Currently I use Firebase auth – A.W. Jul 27 '21 at 13:16

4 Answers4

33

Update 03 Dec 2021

After re:Invent 2021, "Amplify Admin UI" was renamed to "Amplify Studio". With extra powers now:

  • automatically translates designs made in Figma to human-readable React UI component code

https://aws.amazon.com/blogs/mobile/aws-amplify-studio-figma-to-fullstack-react-app-with-minimal-programming/

===============

Original Answer

To start, I want to clarify that "Amplify" is an umbrella term for multiple things. We have:

  1. Amplify Libraries (UI/JS)
  2. Amplify CLI (to create cloud-native applications)
  3. Amplify Console (ci/cd and hosting for full-stack web apps)
  4. Amplify Admin UI (UI to create and configure full-stack web apps)

You can check the homepage for more clarification - https://docs.amplify.aws/

Is there a lightweight Cognito-only client library for interfacing with the Cognito service, authentication-and-authorization flow?

Behind the scenes, Amplify uses amazon-cognito-identity-js library to interface with Amazon Cognito. You can install that directly via npm install amazon-cognito-identity-js.

The source code has been moved to the Amplify Libraries (e.g. amplify-js) repository. Once again, is part of the "Amplify" umbrella under the first category "Amplify Libraries".

Is there a way to use Cognito service without Amplify libraries?

Another approach that you can do, is to use Amazon Cognito as an OAuth server. When you create an Amazon Cognito Hosted UI Domain, it provides you an OAuth 2.0 compliant authorization server.

You can create your own API/Backend for Signup/Login endpoints and exchange tokens/credentials with the Amazon Cognito OAuth server without using aws-sdk or any 3rd party dependency library.

I wrote a walkthrough example, how to configure your User Pool, endpoints that you need to talk to using Node.js, you can find it here: https://github.com/oieduardorabelo/node-amazon-cognito-oauth

You can follow the same idea for any other language.

oieduardorabelo
  • 2,687
  • 18
  • 21
  • Thanks for your answer. A follow up question: Would this approach work with login with Google, Facebook, etc. which is a part of the hosted UI or would you have to handle this yourself before communicating with the oauth server? – Michael Nov 21 '22 at 03:13
4

As a result of research on the topic of using Amazon Cognito without Amplify in React, I came across such a sandbox. Switching from router 5 to router 6 probably won't be a problem. The main gold here is this hook. The rest of the implementation can be found in the sandbox: https://codesandbox.io/s/cognito-forked-f02htu

const Pool_Data = {
  UserPoolId: "xxx",
  ClientId: "yyy"
};

export default function useHandler() {
  const [state, setstate] = useState({
    loading: false,
    isAuthenticated: false
  });

  const { loading, isAuthenticated } = state;

  const userPool = new CognitoUserPool(Pool_Data);

  const getAuthenticatedUser = useCallback(() => {
    return userPool.getCurrentUser();
  }, []);

  console.log(getAuthenticatedUser());

  useEffect(() => {
    getAuthenticatedUser();
  }, [getAuthenticatedUser]);

  const signOut = () => {
    return userPool.getCurrentUser()?.signOut();
  };
  console.log("I am here", getAuthenticatedUser()?.getUsername());

  return {
    loading,
    isAuthenticated,
    userPool,
    getAuthenticatedUser,
    signOut
  };
}
MadaShindeInai
  • 432
  • 4
  • 16
3

As mentioned by @oieduardorabelo, you can simply install 'amazon-cognito-identity-js' where you can also find well done examples on npm.

Here is my test code to easily understand this lib. You must have already built the infrastructure on AWS (userPool, userClient and add a new user to test sign in - in my case the user has to change the password on first login so I added this use case on my script):

import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';

var authenticationData = {
  Username: 'email',
  Password: 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
  UserPoolId: 'us-east-1_userpoolid',
  ClientId: '26pjexamplejpkvt'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();

console.log(cognitoUser);

if (!cognitoUser) {

  var userData = {
    Username: authenticationData.Username,
    Pool: userPool
  };
  var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
  cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
      var accessToken = result.getAccessToken().getJwtToken();
      var idToken = result.idToken.jwtToken;
      console.log('Success', accessToken, idToken);
    },
    newPasswordRequired: function (userAttributes, requiredAttributes) {
      delete userAttributes.email_verified;
      cognitoUser.completeNewPasswordChallenge('DemoPassword1!', userAttributes, {
        onSuccess: (data) => {
          console.log(data);
        },
        onFailure: function (err) {
          alert(err);
        }
      });
    },
    onFailure: function (err) {
      alert(err);
    },

  });
}

If someone is interested in setup this test project from scratch run:

npm init -y
npm i -D webpack webpack-cli
npm i amazon-cognito-identity-js

in webpack.config.js:

var path = require('path');

module.exports = {
  entry: './src/app.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: 'main.js',
  }
}

Create a new file in ./src/app.js where add the previous amazonCognitoIdentity code with the right AWS info ref and create ./dist/index.html whith:

...
<body>
  <script src="main.js"></script>
</body>

in package.json add script "watch":

...
"scripts": {
    "watch": "webpack --watch",
}

Finally run it:

npm run watch

and open the index.html directly on the browser with dev console as well.

Hopefully useful for someone.

70X
  • 320
  • 1
  • 5
  • 14
-1

I wrote an article a couple of years ago explaining how to do this.

The article talks about Amplify but as was mentioned in another response, that's more of an umbrella term, in the article we are using mostly UI components provided by the Amplify project.

you can find it here: https://medium.com/@mim3dot/aws-amplify-cognito-part-2-ui-components-935876fabad3

mim
  • 1,301
  • 14
  • 24
  • The question was how to use without Amplify, but you giving an article that contains example if usage with Amplify. – MadaShindeInai May 12 '22 at 13:54
  • @MadaShindeInai, I explained in my reply why that doesn't matter: | > The article talks about Amplify but as was mentioned in another response, that's more of an umbrella term, in the article we are using mostly UI components provided by the Amplify project. – mim May 13 '22 at 19:45
  • 4
    It's completely matter. Author asks about amazon-cognito-identity-js or AWS SDK, and tells that Amplify is not a way he want. And in your article you are using only Amplify stuff ( UI and Amplify's build in logic based on amazon-cognito-identity-js). There are NO examples of solutions that are relevant for providing logic without Amplify but with amazon-cognito-identity-js. You just wrapping your app with HOC. – MadaShindeInai May 14 '22 at 14:51
  • Hmmm, alright, I think you may not know a lot about the topic as I already explained this in my response so what you are saying is essentially repeating what I have already said, I'm of course not forcing this to OP, just trying to help. these messages in the other hand, do not help anyone! I do not get your point! – mim May 15 '22 at 15:46