Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Authentication & Authorization

Passport.js Authentication Middleware

Node.js authentication middleware with Passport.js and various strategies

Samples

Entries inside this sample collection

CodejavascriptIntermediate

Passport.js Local Strategy

Local username/password authentication with Passport.js

Difficulty

5/10

Estimated time

15 min

Tags

passport, authentication, local, security

Prerequisites

Node.js, Express.js, Passport.js

javascript
// Passport.js Local Strategy Setup
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const express = require('express');

// User database (in production, use a real database)
const users = {
  'john@example.com': {
    id: 1,
    email: 'john@example.com',
    password: bcrypt.hashSync('password123', 10),
    name: 'John Doe'
  }
};

// Local Strategy
passport.use(new LocalStrategy(
  {
    usernameField: 'email',
    passwordField: 'password'
  },
  async (email, password, done) => {
    try {
      const user = users[email];
      if (!user) {
        return done(null, false, { message: 'User not found' });
      }

      const isValid = await bcrypt.compare(password, user.password);
      if (!isValid) {
        return done(null, false, { message: 'Invalid password' });
      }

      return done(null, user);
    } catch (error) {
      return done(error);
    }
  }
));

// Serialize/deserialize user
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
  const user = Object.values(users).find(u => u.id === id);
  done(null, user);
});

// Express app setup
const app = express();
app.use(express.json());
app.use(require('express-session')({ secret: 'secret' }));
app.use(passport.initialize());
app.use(passport.session());

// Authentication middleware
const authMiddleware = (req, res, next) => {
  if (req.isAuthenticated()) {
    return next();
  }
  res.status(401).json({ error: 'Unauthorized' });
};

// Routes
app.post('/login', passport.authenticate('local'), (req, res) => {
  res.json({ user: req.user });
});

app.get('/profile', authMiddleware, (req, res) => {
  res.json({ user: req.user });
});

app.post('/logout', (req, res) => {
  req.logout();
  res.json({ message: 'Logged out' });
});

app.listen(3000, () => console.log('Server running on port 3000'));
CodejavascriptIntermediate

Passport.js Google OAuth 2.0

Google OAuth 2.0 authentication with Passport.js

Difficulty

6/10

Estimated time

20 min

Tags

passport, google, oauth2, social, authentication

Prerequisites

Node.js, Google Console, OAuth 2.0

javascript
// Passport.js Google OAuth 2.0
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const express = require('express');
const app = express();

// Google Strategy
passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: '/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
  // Find or create user in your database
  const user = {
    id: profile.id,
    email: profile.emails[0].value,
    name: profile.displayName,
    avatar: profile.photos[0].value
  };

  return done(null, user);
}));

// Routes
app.get('/auth/google', passport.authenticate('google'));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.redirect('/dashboard');
  }
);

// Middleware to check authentication
const ensureAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) return next();
  res.redirect('/');
};
CodejavascriptIntermediate

Passport.js JWT Strategy

JWT authentication with Passport.js for APIs

Difficulty

6/10

Estimated time

15 min

Tags

passport, jwt, authentication, api, security

Prerequisites

Node.js, JWT concepts, APIs

javascript
// Passport.js JWT Strategy
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();
app.use(express.json());

// JWT Strategy
passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'your-secret-key'
}, (payload, done) => {
  // Find user by ID from payload
  const user = { id: payload.sub, email: payload.email };
  return done(null, user);
}));

// Generate JWT token
function generateToken(user) {
  return jwt.sign(
    { sub: user.id, email: user.email },
    'your-secret-key',
    { expiresIn: '1h' }
  );
}

// Login route
app.post('/login', (req, res) => {
  // Validate credentials (simplified)
  const user = { id: 1, email: req.body.email };
  const token = generateToken(user);

  res.json({ token, user });
});

// Protected route middleware
const authMiddleware = passport.authenticate('jwt', { session: false });

// Protected API route
app.get('/api/profile', authMiddleware, (req, res) => {
  res.json({ user: req.user });
});
CodejavascriptComplex

Custom Passport Strategy

Creating custom authentication strategies with Passport.js

Difficulty

7/10

Estimated time

20 min

Tags

passport, custom, api key, advanced

Prerequisites

Node.js, Passport.js, Custom strategies

javascript
// Custom Passport Strategy
const passport = require('passport');
const { Strategy } = require('passport-strategy');
const express = require('express');
const app = express();

// Custom API Key Strategy
class ApiKeyStrategy extends Strategy {
  constructor(verifyCallback) {
    super();
    this.name = 'apikey';
    this.verify = verifyCallback;
  }

  authenticate(req, options) {
    const apiKey = req.query.apiKey || req.headers['x-api-key'];
    if (!apiKey) {
      return this.fail({ message: 'API key required' });
    }

    // Validate API key against database
    this.verify(apiKey, (err, user) => {
      if (err) return this.error(err);
      if (!user) return this.fail({ message: 'Invalid API key' });
      return this.success(user);
    });
  }
}

// Use custom strategy
passport.use('apikey', new ApiKeyStrategy(
  (apiKey, done) => {
    // Database lookup
    const validKeys = {
      'key123': { id: 1, name: 'App 1' },
      'key456': { id: 2, name: 'App 2' }
    };

    const user = validKeys[apiKey];
    done(null, user);
  }
));

// API endpoint with custom auth
app.get('/api/data',
  passport.authenticate('apikey', { session: false }),
  (req, res) => {
    res.json({ data: 'Protected data', user: req.user });
  }
);

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

JSON Field Extraction, Transformation, and Provenance

Extract selected JSON fields by path, reshape the payload with JSONata, and record field-level provenance without claiming business-semantic validation.

Hub

JSON Normalization and Interchange Workflow

Turn a structured source into a checked JSON representation, then export the exact table, configuration, document, API, XML, CSON, EDN, BSON, or UBJSON form required downstream.

Hub

Node.js Release Dependency and License Review

Freeze a Node.js release inventory, review dependency declarations and an external SBOM against an approved license policy, compare changes and deliver traceable approval evidence.

Home
Tools3212
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Validation

Passport Validator

Validate passport numbers from different countries (China, USA, Japan, etc.)

Authentication & Authorization

OAuth 2.0 & OpenID Connect Samples

OAuth 2.0 authorization framework and OpenID Connect authentication protocol examples

Authentication & Authorization

OAuth 2.0 Samples

OAuth 2.0 implementation examples including authorization flows, client configurations, and security best practices

Security

JWT Samples

Comprehensive JWT examples from basic token structure to advanced security implementations

Security

Zero Trust Architecture Samples

Comprehensive Zero Trust architecture samples covering identity authentication, network segmentation, micro-segmentation strategies, and secure access control

Web Frameworks

Koa Samples

Koa Node.js middleware framework examples including middleware chaining, context handling, async/await patterns, and ecosystem integration

Authentication & Authorization

Casbin Access Control Library

Powerful and efficient open-source access control library