Using AWS Cognito with React

Hey,

I have a React App and I am trying to use AWS Cognito. However, as soon as I refresh the page (a fairly normal action for any end-user, the user is no longer authenticated. I’m confused about what to do about this. Any suggestions? Sorry, I’m a newbie

You need to get thr token from cognito amf store in a session store. Use that to authenticate. You might be deleting that token ?

Difficult to give tips without having access to your code.
Evidently refreshing deletes your variable values. Where/how do you store them?

Can you debug and set a breakpoint to see which paths of your code are being executed when you reload?

Hi, you have to save auth/refresh tokens into the session storage and on refresh the page, check is token still valid.

Or better to use amplify auth components and do not worry about auth anymore.

https://docs.amplify.aws/ui/auth/authenticator/q/framework/react/

I’m not using Amplify. I’m not sure how much it’ll end up costing me and am fairly constrained on budget. Is that silly? Should Amplify on free trial be okay?

Aah I see. So I store it in a cookie? I thought that the dependency takes care of that

you pay only for the underlying AWS services you use. There are no additional charges for using the Amplify Framework.

https://aws.amazon.com/amplify/pricing/

I do t know where to but somewhere as am not a front end developer. But yes session store or cookie are the options I think

I do t know where to but somewhere as am not a front end developer. But yes session store or cookie are the options I think

Read about session storage basics here: https://www.javascripttutorial.net/web-apis/javascript-sessionstorage/

This is different to a cookie. This is about storing a piece of data, temporarily, via the user’s browser.


As /u/ebykka said though you could look at AWS Amplify, which is a library that takes away some of this complexity for you. This has some documentation on how to do that: https://docs.amplify.aws/ui/auth/authenticator/q/framework/react/#recommended-usage


If you want the most simple answer, then just use sessionStorage. But if this is for a larger AWS related project, AWS Amplify does reduce a lot of complexity long term.

This. Amplify makes auth super trivial and then you don’t have a bunch of home grown auth code in your app.

Here’s what you do.

  1. Install aws-amplify.
  2. In your root, do this:

import Amplify from “aws-amplify”;

Amplify.configure({
Auth: {
// REQUIRED - Amazon Cognito Region
region: “eu-west-1”,

// OPTIONAL - Amazon Cognito User Pool ID
userPoolId: process.env.REACT_APP_USER_POOL_ID,

// OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
userPoolWebClientId: process.env.REACT_APP_CLIENT_ID,

// OPTIONAL - Enforce user authentication prior to accessing AWS resources or not
mandatorySignIn: false,

// OPTIONAL - Manually set the authentication flow type. Default is ‘USER_SRP_AUTH’
authenticationFlowType: “USER_PASSWORD_AUTH”,
},
});

  1. Then in your App.js, or whichever component you land on after authenticating:

import { Auth } from “aws-amplify”;

useEffect(() => {
async function onLoad() {
try {
const user = await Auth.currentAuthenticatedUser();
console.log(user);
setAuthenticated(true);
} catch (e) {
if (e !== “No current user”) {

			}
		}
	}
            onLoad()
    }, []);

Amplify.

If you can’t use Amplify for whatever reason, let me know, I’ll show you how to do it in Cognito.

General procedure: Once the token is retrieved store it in the application’s memory.

  1. Where in the memory depends on your design. It could be cookies, local storage, session storage, etc, (Any sort of cache or application memory you have available)

  2. Make sure to add a time to live if you store it on cache/local storage/cookies.

Specific implementation:

Use next-auth (https://next-auth.js.org/providers) to handle the process for you. Consume your 0Auth2 flow from Cognito (or the flow you are using to retrieve the tokens) and you are done.

You do not need amplify framework as backend. Use only amplify browser(reactjs) components. It’s open-source and free.

I mean home grown auth is sometimes preferable to storing authentication tokens in session storage…

This is the answer

Sure. But he says “Sorry, I’m a newbie” which is probably a strong indicator that the need for home grown auth code is not there for this particular thread. And the tone seems to indicate wanting auth to just work, not necessarily that OP is trying to learn auth techniques.

awesome ty