The Complete Guide to React Authentication with Auth0

Edit:

After looking at the requests being sent in the dev console I saw that only the response_mode parameter “web_message” was throwing errors. From the documentation I saw:

This response mode is defined in OAuth 2.0 Web Message Response Mode specification. It uses HTML5 Web Messaging instead of the redirect for the authorization response from the /authorization endpoint. This is particularly useful when using Silent Authentication. To do this response mode, you must register your app’s URL at the Allowed Web Origins field in your Auth0 application settings.

Obviously, I had forgotten to put the URL in the Allowed Web Origins section in the settings.

For the authors: Since I’m a beginner and I stumbled upon this issue, maybe it’s useful to explain how the caching works and that you have to set up the Allowed Web Origins field as well. Right now, I know that it works but am not sure how the response_mode web_message works.


Old:

Hi guys,

I’ve been going through this guide and implemented my own react app.
However, I have the problem that the user information will not be cached for navigation after the login.

So what happens is that the user logs in & I can render user information. However, as soon as I navigate to a different page the user is cleared and has to login again.

Now, from the guide I understand that Auth0Context should provide & cache that user information. In order to expose the Auth0Context to child components of my app, I have to wrap the <Auth0Provider/> component around it, which I did. Also, I push the redirect call to React Router’s history with the <Auth0ProviderWithHistory /> component.
From my understand this should be sufficient for Auth0 Provider to correctly cache the user information, which it unfortunately does not do.
Here’s a screenshot of the hierarchy of React components after a successful login (but, like I said, upon navigation it will clear the authentication).

1 Like

@dan-auth0 Thank you again for the quick response. This blog covers most of what we need (authentication, private routes with redirect, and I see the link to the Secure API article you mentioned).

I’m not clear on how the API scope and permission settings would be accessed to control which elements are visible on the page. I initially referred to this blog (https://auth0.com/blog/role-based-access-control-rbac-and-react-apps/) to setup role based rendering of specific components. However, it’s a little too easy to hack. I’d love to tap into the permissions and scope in the token to control this.

1 Like

Hi Auth0 Team,
I am having an issue with the SecureRoute HOC. When I use this component to secure routes my app always redirects to the login page even if the user has already logged in. How do I edit this component so that once the user is logged in they don’t get redirected again? For clarification, the user isn’t forced to log in again, it just redirects to the page then realizes that they are logged in and redirects back, however this blip in between every page is very annoying.

Any and all help would be greatly appreciated

1 Like

Hi there,

the tutorial is a great starting point for the first steps with Auth0 and React.
I would be interested in the next steps. In my understanding, the data should not be kept directly in the components, but should be stored e.g. in a Redux Store. In that case the data would also be queried there. Therefore the token has to accessible in the store. A tutorial about React and Redux was already mentioned here. Is there already something new about it?

From my point of view there can be two approaches:

  • Using the useAuth0 hooks and passing the token to every fetch action in the store (seems to be generate some overhead)
  • Determining the current token in the store (but then the use of the hooks (as far as I know) is not possible)

Are there any ideas / approaches how this integration is thought of by you?

If I’d like to follow my second approach, it’s probably better to use the SPA SDK instead of the React SDK, right?

Thanks for your feedback. :slight_smile:

1 Like

Howdy, Richard! Thank you for joining the Auth0 community, reading the post, and sharing your feedback. We include an instruction to add an entry to the “Allowed Web Origins” field in the React guide :thinking: However, I am not certain if its omission does lead to this unexpected behavior of not persisting user profile information during navigation. I’ll research more on this.

@avala Correct, anything done in the client rendered in the browser has the potential of being altered by a malicious user. The key is to have checks in place in the backend as well to ensure that the client only gets hydrated with information if it does indeed have the right to access that information: it can send an access token. If it doesn’t and a cheeky user changes the frontend code to set the “admin” property to true, the client won’t get any data because there is no access token with those permission. The backend will reply with “404” or “500” something like that. Then the client will render an error page or redirect the user.

Thank you for the questions that you have been asking as they are helping me validate the content that I need to include in the follow ups :slight_smile:

The RBAC + React blog post that you mentioned is something I am looking to update or rewrite to follow our best practices on that topic. We are currently researching internally on what that should be. I’d recommend not using that as a guide just yet. I’ll add a note warning readers about that today :+1:

Howdy, Andrew. Thank you for reading the blog post. To better assist you, could you please expand on what the SecureRoute HOC is? Is that your adaptation of the PrivateRoute component from the guide?

Additionally, could you provide us with some sample code that showcases this error, please? For example, you could create a CodeSandbox React app that exhibits that behavior or a GitHub rep, please. Just be sure to not include your Auth0 variables in there :slight_smile:

Howdy, Janna! Welcome to the Auth0 Community. That’s a great question on Redux. We’ve experienced limited bandwidth during these times so I have not been able to advanced on that front. I am currently working on researching best practices for React + Role-Based Access Control.

I checked with one of the SDK teammates and he mentioned that we don’t have any specific recommendation on integrating the artifacts stored by the SDK with the Redux store. He mentioned that he wouldn’t personally keep the user in the store and, instead, he’d use the two libraries side by side.

It’s an interesting use case :slight_smile: I’ll keep you updated on any guidance that we create on Redux.

Hi, thank you for this, but I wonder if you could help shed a little more light for those of us using class components. The issue I’m having that doesn’t seem to be addressed anywhere online is why I’m getting a different token when using this.props.auth0.getAccessTokenSilently() vs using the hook via const { getAccessTokenSilently } = useAuth0();

1 Like

Ryan, would you benefit from seeing the sample app I use in the blog post built with classes? If so, I could do that for you and have it ready by the end of the week.

1 Like

Glory be, I surely would!

1 Like

@ryanbuckleyca ,

You can find the same application implemented with classes on the auth0-react-sample-classes I’ve created.

Warning: :eyes: This application is using v2 of the React Guide with a different approach to the application architecture. The new version of the guide should go live some time this week. You are getting a sneak peak! v2 still uses Hooks and Function components though, so it’s handy to have this code sample with classes around.

1 Like

@dan-auth0,

The auth0-provider-with-history was not redirecting users correctly; they would always redirect to the home page. After some investigation, it looks like BrowserRouter ignores this history prop. I updated the app.js file and the onRedirectCallback started working correctly.

Does NOT work:
import { BrowserRouter as Router, Route, Switch, useHistory } from 'react-router-dom';

Does work:

import { Router, Route, Switch, useHistory } from ‘react-router-dom’;

2 Likes

Thanks for sharing it with the rest of community!

Hello! Thanks for this great tutorial! I’ve been able to get everything working, right up until the end with the private api endpoint.

I’m getting a ERR_ABORTED 500 (Internal Server Error) message in the browser and a 401 UnauthorizedError: No authorization token was found in the server

However, I DO see that the audience is being sent in the payload of the jwt token:

{
  "iss": "https://<my tenant>.auth0.com/",
  "sub": "...,
  "aud": [
    "https://express.sample",
    "https://<my tenant>.auth0.com/userinfo"
  ],
  "iat": ...,
  "exp": ...,
  "azp": ...,
  "scope": "openid profile email"
}

Do you have any suggestions on why it isn’t working? I cloned auth0-express-js-sample repo for the server and auth0-react-sample for the FE. I had to make some small changes (like updating the process env variables for these to match AUTH0_ISSUER API_PORT and APP_ORIGIN ) but otherwise I believe everything should match what is here in this tutorial.

Very much appreciated!

1 Like

Thanks, Avala, for sharing this observation. I’ll test this out and update the blog post accordingly. I bumped into this over the weekend on another app.

Howdy, Claire! Thank you for reading the blog post and for your feedback. When you use the exact same variable values and names as described in the blog post, does it work?

I just cloned both repos (Express API and React) and I got them working without errors :thinking:

A few issue that come up in relation to client-server connection can relate to:

  • Ensure that the issuer URL has the trailing slash.
  • Ensure that you whenever you change an environmental variable, you restart the application.
  • Ensure that you logout and log back in after you set up the React SDK with the audience parameter.

But from the error that you are getting, the access token does have the audience value :thinking: Yet, for some reason the Express server is rejecting it as invalid.

Avala,

i tried this out by cloning the apps fresh. I can click on the “Profile” or “External API” tab, log in using the Auth0 Universal Login page, and then I am taken back to the corresponding view (Profile or External API), not the home page. :thinking:

Is the authentication flow where you experienced the home-page-only redirect the same as mine or did something else take place?

Hello,

I’m new to the auth0 community and this is my first time using auth0. I followed your tutorial but got stuck when I tried to login. The site said:

This site can’t be reached

undefined ’s server IP address could not be found.

Please where did I go wrong? @dan-auth0

Hello, Somto. Welcome to the Auth0 Community. :thinking: Are there any errors on the browser’s Developer console?
Could you check that you have set up the variables in .env correctly, please?