# Express login with express-openid-connect

## 1. Install and env

`npm install express-openid-connect dotenv`

`.env`:

```
SECRET [a 32+ byte random hex string]
BASE_URL [your app base URL]
CLIENT_ID [your value]
ISSUER_BASE_URL https://YOUR-TENANT-DOMAIN
```

Generate the secret value `openssl rand -hex 32`. It encrypts the session cookie. Rotating it logs everyone out; keep it stable in production.

## 2. Middleware

```
require("dotenv").config();
const express = require("express");
const { auth } = require("express-openid-connect");

const config = {
  authRequired: false,
  auth0Logout: true,
  "secret": process.env.SECRET,
  baseURL: process.env.BASE_URL,
  clientID: process.env.CLIENT_ID,
  issuerBaseURL: process.env.ISSUER_BASE_URL,
};

const app = express();
app.use(auth(config));
```

The middleware mounts `/login`, `/logout`, `/callback` automatically. `authRequired: false` keeps routes public until you guard them.

## 3. Guard routes

```
const { requiresAuth } = require("express-openid-connect");
app.get("/profile", requiresAuth(), (req, res) => {
  res.json(req.oidc.user);
});
```

## 4. Register URLs

Application type: Regular Web Application. Allowed Callback URLs must contain `BASE_URL` + `/callback` exactly. If the app sits behind a proxy or load balancer, set `app.set("trust proxy", 1)` or the computed baseURL mismatches and the callback is rejected.

## Checklist

- issuerBaseURL uses your tenant domain (or custom domain) with https.
- Session secret is long, random, and stable.
- Callback URL registered character-for-character, protocol included.