Login with AWS Cognito
We are going to use AWS Amplify to login to our Amazon Cognito setup. Let’s start by importing it.
Import Auth from AWS Amplify
Add the following to the header of our Login container in src/containers/Login.js
.
import { Auth } from "aws-amplify";
Login to Amazon Cognito
The login code itself is relatively simple.
Simply replace our placeholder handleSubmit
method in src/containers/Login.js
with the following.
handleSubmit = async event => {
event.preventDefault();
try {
await Auth.signIn(this.state.email, this.state.password);
alert("Logged in");
} catch (e) {
alert(e.message);
}
}
We are doing two things of note here.
-
We grab the
email
andpassword
fromthis.state
and call Amplify’sAuth.signIn()
method with it. This method returns a promise since it will be logging the user asynchronously. -
We use the
await
keyword to invoke theAuth.signIn()
method that returns a promise. And we need to label ourhandleSubmit
method asasync
.
Now if you try to login using the admin@example.com
user (that we created in the Create a Cognito Test User chapter), you should see the browser alert that tells you that the login was successful.
Next, we’ll take a look at storing the login state in our app.
For help and discussion
Comments on this chapterIf you liked this post, please subscribe to our newsletter, give us a star on GitHub, and follow us on Twitter.