How to integrate a Express Backend with an Auth0 frontend for controlled access to server routes?

Hello,

I am new to Auth0 and MongoDB and started working on a website for an organization that needs layers of permissions.

My backend runs Express.js which connects to MongoDB, and my frontend runs client-side rendering React.js.

I have a basic project with a single sign-in and sign-out button from this tutorial here: https://www.youtube.com/watch?v=pAzqscDx580

How can I secure my express backend routes such that only certain users can access them?

My idea is that each backend route requires a user token, passed as a URL param, to access. I then use auth0 on the backend to figure out who this user is, and I then check the MongoDB database to see the user’s permissions. If the user’s permissions allow them to access this server route, I complete the task for that route.

These routes include accessing MongoDB.

How would I go about implementing this? Is there a better option?

3 Likes

Hello @michaelnicol71 welcome to the community!

I recommend checking out the express-oauth2-jwt-bearer package - Here’s a quickstart which should be helpful and FWIW our react sample uses this package as well.

This sounds about right! Just make sure you are passing an access token as opposed to ID token.

2 Likes

I am now attempting to set up scopes, roles, and permissions for users accessing routes.

For reference, here is the example quickstart code:

// server.js
const { requiredScopes } = require('express-oauth2-jwt-bearer');

const checkScopes = requiredScopes('read:messages');

app.get('/api/private-scoped', checkJwt, checkScopes, function(req, res) {
  res.json({
    message: 'Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.'
  });
});

How can I access the user’s information inside of the route?

Two people might have the scope of “all:email” in their role, but depending on who that user is, the people they have access to email will vary.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.