Auth0 in React and Node
Tags: auth0, react, node
Published: 2023-02-27 04:15:45

I recently implemented Auth0 in my personal side project. If you're interested in learning how to implement it in React and Node, feel free to take a look.

{% embed https://github.com/xychenxy/pirate-shopping %}

> **OAuth 2.0** is the industry-standard protocol for authorization. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. Ref from https://oauth.net/2/

> **Auth0** is a software product that implement the OAuth 2.0 protocol. 


<br/>
<br/>

### The flow

The graph below illustrates that the client will receive two types of tokens (access and refresh) from the Authorization Server. The access token serves to protect the client's resources, while the refresh token enables the client to obtain new access and refresh tokens.


![A pie chart showing 40% responded "Yes", 50% responded "No" and 10% responded "Not sure"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hp7e6jv1jojzboss13nm.png)


### Let's see how to implement auth0 in react and node

#### React side
In react codebase, install @auth0/auth0-react

```javascript
<Auth0Provider
	domain={import.meta.env.VITE_AUTH0_DOMAIN}
	clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
	authorizationParams={{
		redirect_uri: window.location.origin,
		audience: import.meta.env.VITE_AUTH0_AUDIENCE,
	}}
	onRedirectCallback={onRedirectCallback}
	// scope="read:current_user"
>
	{children}
</Auth0Provider>;
```

You also can use `getAccessTokenSilently()` to get new access token, see below example. 

For some protected resources requests, make sure adding Bearer token into your request
```javascript
headers: {Authorization: `Bearer token`} 
```


```javascript
useEffect(() => {
	try {
		const fetchAccessToken = async () => {
			const newAccessToken = await getAccessTokenSilently({
				authorizationParams: {
					audience: import.meta.env.VITE_AUTH0_AUDIENCE,
					scope: "read:current_user",
				},
			});

			localStorage.setItem("token", newAccessToken);
		};
		if (isAuthenticated) {
			fetchAccessToken();
		}
	} catch (e: Error) {
		console.log("error", e.message);
	}
}, [getAccessTokenSilently, isAuthenticated]);
```

#### Node side
In node codebase, `express-jwt` and `jwks-rsa` are useful to do the jwt check with auth0:
```javascript
const jwtCheck = jwt({
	secret: jwks.expressJwtSecret({
		cache: true,
		rateLimit: true,
		jwksRequestsPerMinute: 5,
		jwksUri: `https://${process.env.auth0_domain}/.well-known/jwks.json`,
	}),
	audience: process.env.audience,
	issuer: `https://${process.env.auth0_domain}/`,
	algorithms: ["RS256"],
});
```

Sometimes, if you want to get user info, it's not a good idea to put user info in your request, we can do it in this way:
```javascript

const userInfo = await axios
	.get(`https://${process.env.auth0_domain}/userinfo`, {
		headers: {
			Authorization: req.headers.authorization,
		},
	})
	.then((response) => {
		return response.data;
	});
```

### Summary
Auth0 is a great product that allows us to implement authentication process quickly. Why not give it a try?