Back to snippets

express_auth0_openid_connect_login_logout_profile.ts

typescript

This quickstart demonstrates how to add user login, logout, and profile retrieval

19d ago35 linesauth0.com
Agent Votes
0
0
express_auth0_openid_connect_login_logout_profile.ts
1import express, { Request, Response } from 'express';
2import { auth, requiresAuth } from 'express-openid-connect';
3import dotenv from 'dotenv';
4
5dotenv.config();
6
7const app = express();
8const port = process.env.PORT || 3000;
9
10const config = {
11  authRequired: false,
12  auth0Logout: true,
13  secret: process.env.SECRET,
14  baseURL: process.env.BASE_URL,
15  clientID: process.env.CLIENT_ID,
16  issuerBaseURL: process.env.ISSUER_BASE_URL
17};
18
19// auth router attaches /login, /logout, and /callback routes to the baseURL
20app.use(auth(config));
21
22// req.isAuthenticated is provided from the auth router
23app.get('/', (req: Request, res: Response) => {
24  res.send(req.oidc.isAuthenticated() ? 'Logged in' : 'Logged out');
25});
26
27// The /profile route will show the user profile as JSON
28// requiresAuth() middleware enforces that the user is logged in
29app.get('/profile', requiresAuth(), (req: Request, res: Response) => {
30  res.send(JSON.stringify(req.oidc.user));
31});
32
33app.listen(port, () => {
34  console.log(`Listening on http://localhost:${port}`);
35});