Git Product home page Git Product logo

jwt-passport's Introduction

Passport.js framework that uses JWT for sessions

This is an alternative framework for Passport.js that is designed to use JWT tokens for sessions. So that, instead of storing user's ID and metadata in a database (e.g. Redis), it encodes that data into a JSON Web Token and writes that token to a session cookie.

How to Install

$ npm install jwt-passport

Note: It requires Node.js 6.11 or higher

How to Use

const uuid = require('uuid');
const express = require('express');
const passport = require('passport');
const jwt = require('jwt-passport');

// We're using Knex.js database client in this examle,
// but it could be any other database driver.
const db = require('./db');

passport.framework(
  jwt({
    name: '__session',
    secret: '<secret>',
    audience: '<audience>',
    issuer: '<issuer>',
    expiresIn: '1 hour',

    // Prepare payload for an ID token
    createToken: req => ({
      sub: req.user.id,
      jti: uuid.v4(),
    }),

    // Save user's token in a database
    saveToken: token =>
      db
        .table('user_tokens')
        .insert({
          user_id: token.sub,
          token_id: token.jti,
        }),

    // Revoke user's token
    deleteToken: token =>
      db
        .table('user_tokens')
        .where({ token_id: token.jti })
        .del(),

    // Check if the token was not revoked and find the corresponding user
    findUser: token =>
      db
        .table('user_tokens')
        .leftJoin('users', 'users.id', 'user_tokens.user_id')
        .where({ 'user_tokens.token_id': token.jti })
        .select('users.*')
        .first(),
  });
);

passport.use(new FacebookStrategy(/* config */));
passport.use(new TwitterStrategy(/* config */));

const app = express();

// Extend the HTTP request object with
// req.logIn() and req.logOut() helper methods
app.use(passport.initialize());

// Attemp to parse session cookie, validate the token
// and put the authenticated user object onto the contxt (req.user)
app.use(passport.session());

app.get('/', (req, res) => {
  res.send(`Welcome, ${req.user ? req.user.displayName : 'guest'}!`);
});

app.get('/login/:provider', (req, res, next) => {
  passport.authenticate(req.params.provider, /* options */)(req, res, next);
});

app.get('/login/:provider/return', (req, res, next) => {
  passport.authenticate(req.params.provider, /* options */)(req, res, next);
});

Related Projects

License

Copyright © 2018-present Kriasoft. This source code is licensed under the MIT license.

jwt-passport's People

Contributors

koistya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

isabella232

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.