DEV Community

Mavis
Mavis

Posted on

Auth0 in React and Node

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.

pirate-shopping

The pirate shopping project is one of my side projects that allows me to keep adding some tech to advance my skillset.


To do list breakdown


Tech

Front-end

React 18, vite, TypeScript, Redux, Hooks, Firebase, Auth0 Login, CSS-in-JS

Backend

Node/Express framework

Others

AWS, Docker, GitHub Action, Netlify


How to run it

Please make sure docker have already installed.

Run ./run_docker.sh dev|prod

Production

docker build . -t xychenxy/pirate-shopping docker run -it -p 5000:5000 -e "NODE_ENV=production" 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.

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"

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

React side

In react codebase, install @auth0/auth0-react

<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>;
Enter fullscreen mode Exit fullscreen mode

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

headers: {Authorization: `Bearer token`} 
Enter fullscreen mode Exit fullscreen mode
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]);
Enter fullscreen mode Exit fullscreen mode

Node side

In node codebase, express-jwt and jwks-rsa are useful to do the jwt check with auth0:

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"],
});
Enter fullscreen mode Exit fullscreen mode

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:


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

Summary

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

Top comments (2)

Collapse
 
lico profile image
SeongKuk Han • Edited

Great :)
I just have one suggestion, I think that would be bertter if you use code highlighting :) Just one of my opinion.

const userInfo = await axios.get('https://test.com/v1/test');
Enter fullscreen mode Exit fullscreen mode

Instead of

const userInfo = await axios.get('https://test.com/v1/test');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mavis_chen profile image
Mavis

Nice, let me try to use it, Thank you!