DEV Community

Cover image for Auth0 integration - Node.js + ExpressJS
Franklin Thaker
Franklin Thaker

Posted on

Auth0 integration - Node.js + ExpressJS

This is a simple guide to demonstrate backend Auth0 integration. There will be no frontend involved. User sign-up, log-in, log-out, all operations will be done through backend only.

// index.js
require('dotenv').config();
const { auth, requiresAuth } = require("express-openid-connect");
const app = require("express")();

const config = {
  authRequired: false,
  auth0Logout: true,
  secret: process.env.CLIENT_SECRET,
  baseURL: "http://localhost:3000",
  clientID: process.env.CLIENT_ID,
  issuerBaseURL:`https://${process.env.AUTH0_TENANT}.auth0.com`,
};

// auth router attaches /login, /logout, and /callback routes to the baseURL
app.use(auth(config));

// req.isAuthenticated is provided from the auth router
app.get("/", (req, res) => {
  res.send(req.oidc.isAuthenticated() ? "Logged in" : "Logged out");
});

app.get("/profile", requiresAuth(), (req, res) => {
  res.send(JSON.stringify(req.oidc.user));
});

app.listen(3000);

Enter fullscreen mode Exit fullscreen mode

Environment Variables

To run this project, you will need to add the following environment variables to your .env file

CLIENT_ID -> Go to Auth0 -> Applications -> Settings -> Client ID

AUTH0_TENANT -> Go to Auth0 -> Applications -> Settings -> Domain

CLIENT_SECRET -> Run this command to generate the secret value:

openssl rand -hex 32

If you are running on Windows: Try to run this in Git Bash it should work without you needing to install Win64 OpenSSL
Also make sure to setup this in Settings tab in Auth0:

Allowed Callback URLs: http://localhost:3000
Allowed Logout URLs: http://localhost:3000

References
https://github.com/FranklinThaker/auth0-integration-nodejs
https://auth0.github.io/express-openid-connect/index.html

Top comments (0)