passport-jwt (2024)

passport-jwt (1)passport-jwt (2)

A Passport strategy for authenticating with aJSON Web Token.

This module lets you authenticate endpoints using a JSON web token. It isintended to be used to secure RESTful endpoints without sessions.

Supported By

If you want to quickly add secure token-based authentication to Node.js apps, feel free to check out Auth0's Node.js SDK and free plan at auth0.com/developers passport-jwt (3)

Install

npm install passport-jwt

Usage

Configure Strategy

The JWT authentication strategy is constructed as follows:

new JwtStrategy(options, verify)

options is an object literal containing options to control how the token isextracted from the request or verified.

  • secretOrKey is a string or buffer containing the secret(symmetric) or PEM-encoded public key (asymmetric) for verifying the token'ssignature. REQUIRED unless secretOrKeyProvider is provided.
  • secretOrKeyProvider is a callback in the format function secretOrKeyProvider(request, rawJwtToken, done),which should call done with a secret or PEM-encoded public key (asymmetric) for the given key and request combination.done accepts arguments in the format function done(err, secret). Note it is up to the implementer to decode rawJwtToken.REQUIRED unless secretOrKey is provided.
  • jwtFromRequest (REQUIRED) Function that accepts a request as the onlyparameter and returns either the JWT as a string or null. SeeExtracting the JWT from the request formore details.
  • issuer: If defined the token issuer (iss) will be verified against thisvalue.
  • audience: If defined, the token audience (aud) will be verified againstthis value.
  • algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"].
  • ignoreExpiration: if true do not validate the expiration of the token.
  • passReqToCallback: If true the request will be passed to the verifycallback. i.e. verify(request, jwt_payload, done_callback).
  • jsonWebTokenOptions: passport-jwt is verifying the token using jsonwebtoken.Pass here an options object for any other option you can pass the jsonwebtoken verifier. (i.e maxAge)

verify is a function with the parameters verify(jwt_payload, done)

  • jwt_payload is an object literal containing the decoded JWT payload.
  • done is a passport error first callback accepting argumentsdone(error, user, info)

An example configuration which reads the JWT from the httpAuthorization header with the scheme 'bearer':

var JwtStrategy = require('passport-jwt').Strategy, ExtractJwt = require('passport-jwt').ExtractJwt;var opts = {}opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();opts.secretOrKey = 'secret';opts.issuer = 'accounts.examplesoft.com';opts.audience = 'yoursite.net';passport.use(new JwtStrategy(opts, function(jwt_payload, done) { User.findOne({id: jwt_payload.sub}, function(err, user) { if (err) { return done(err, false); } if (user) { return done(null, user); } else { return done(null, false); // or you could create a new account } });}));

Extracting the JWT from the request

There are a number of ways the JWT may be included in a request. In order to remain as flexible aspossible the JWT is parsed from the request by a user-supplied callback passed in as thejwtFromRequest parameter. This callback, from now on referred to as an extractor,accepts a request object as an argument and returns the encoded JWT string or null.

Included extractors

A number of extractor factory functions are provided in passport-jwt.ExtractJwt. These factoryfunctions return a new extractor configured with the given parameters.

  • fromHeader(header_name) creates a new extractor that looks for the JWT in the given httpheader
  • fromBodyField(field_name) creates a new extractor that looks for the JWT in the given bodyfield. You must have a body parser configured in order to use this method.
  • fromUrlQueryParameter(param_name) creates a new extractor that looks for the JWT in the givenURL query parameter.
  • fromAuthHeaderWithScheme(auth_scheme) creates a new extractor that looks for the JWT in theauthorization header, expecting the scheme to match auth_scheme.
  • fromAuthHeaderAsBearerToken() creates a new extractor that looks for the JWT in the authorization headerwith the scheme 'bearer'
  • fromExtractors([array of extractor functions]) creates a new extractor using an array ofextractors provided. Each extractor is attempted in order until one returns a token.

Writing a custom extractor function

If the supplied extractors don't meet your needs you can easily provide your own callback. Forexample, if you are using the cookie-parser middleware and want to extract the JWT in a cookieyou could use the following function as the argument to the jwtFromRequest option:

var cookieExtractor = function(req) { var token = null; if (req && req.cookies) { token = req.cookies['jwt']; } return token;};// ...opts.jwtFromRequest = cookieExtractor;

Authenticate requests

Use passport.authenticate() specifying 'JWT' as the strategy.

app.post('/profile', passport.authenticate('jwt', { session: false }), function(req, res) { res.send(req.user.profile); });

Include the JWT in requests

The method of including a JWT in a request depends entirely on the extractorfunction you choose. For example, if you use the fromAuthHeaderAsBearerTokenextractor, you would include an Authorization header in your request with thescheme set to bearer. e.g.

Authorization: bearer JSON_WEB_TOKEN_STRING.....

Migrating

Read the Migration Guide for help upgrading to the latestmajor version of passport-jwt.

Tests

npm installnpm test

To generate test-coverage reports:

npm install -g istanbulnpm run-script testcovistanbul report

License

The MIT License

Copyright (c) 2015 Mike Nicholson

To start, I have a robust understanding of authentication mechanisms, particularly with JSON Web Tokens (JWTs) and their integration with Node.js using Passport strategies. Passport is a widely used authentication middleware for Node.js, and I'll provide a comprehensive breakdown of the concepts mentioned in the article you shared.

Concepts Covered:

  1. Passport Strategy with JWT Authentication:

    • Aim: Authenticating endpoints via JSON Web Tokens.
    • Usage: Securing RESTful endpoints without using sessions.
    • Supported By: Auth0's Node.js SDK, specifically passport-jwt.
  2. Installation and Configuration:

    • Installing the passport-jwt module via npm.
    • Configuring the JWT authentication strategy.
    • Defining options for JWT validation (issuer, audience, algorithms, etc.).
    • The verify function to validate JWT payload.
  3. Extracting JWT from Requests:

    • Various methods to extract JWT from requests:
      • Header (fromHeader).
      • Body field (fromBodyField).
      • URL query parameter (fromUrlQueryParameter).
      • Authorization header (fromAuthHeaderWithScheme, fromAuthHeaderAsBearerToken).
      • Custom extractor functions.
    • Configuring extractors using passport-jwt's ExtractJwt.
  4. Authentication and Usage:

    • Using passport.authenticate() with the 'JWT' strategy.
    • Example of authenticating requests (passport.authenticate('jwt', { session: false })).
    • Including JWT in requests based on chosen extractor.
  5. Migrating and Testing:

    • Migration guide for upgrading to the latest major version of passport-jwt.
    • Instructions for testing the setup (npm test and test-coverage reports).
  6. License:

    • passport-jwt using the MIT License.
    • Copyright notice by Mike Nicholson (2015).

This information outlines the comprehensive aspects of setting up JWT-based authentication using Passport in Node.js, covering installation, configuration, request authentication, testing, and migration.

If you have specific questions or need further details about any of these aspects, feel free to ask!

passport-jwt (2024)

FAQs

What does passport JWT do? ›

A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

What is the difference between passport local strategy and JWT? ›

passport-local is the strategy you would use if you are authenticating against a username and password stored 'locally' i.e. in the database of your app - 'local' means local to your application server, not local to the end user. passport-jwt is the strategy for using JSON Web Tokens.

What is the purpose of PassportJS? ›

Passport. js is a popular and modular authentication middleware for Node. js applications. It supports more than 500 authentication strategies, including username and password, OAuth, JWT, and social login.

What is the difference between Nestjs passport and JWT? ›

Passport JS is an authentication middleware for Node JS applications. JSON Web Tokens(JWT) is a token-based authentication system that uses an encrypted token to manage user authentication. To configure the two for user authentication we begin by installing the relevant packages as shown below.

What are JWT used for? ›

A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange. The token is mainly composed of header, payload, signature. These three parts are separated by dots(.).

Is JWT a good idea? ›

Use traditional session-based authentication. It's more secure and flexible than JWT. JWT is a good fit for cases/situations where you want to issue a one-time token to be used for a specific purpose.

Is PassportJS safe? ›

Passport JS is horrible. Sure it's easy to use, but it's not secure, which is kind of the entire point.

What companies use PassportJS? ›

51 companies reportedly use Passport in their tech stacks, including hogangnono, My Franchise, and discord bot.
  • hogangnono.
  • My Franchise.
  • discord bot.
  • Swvl.
  • POLCO.
  • bee10.
  • Development.
  • Build Online.

What is a passport used for? ›

Passports are necessary if you'd like to travel abroad as they verify your identity and nationality. They grant the bearer safe passage and protection in a foreign land. You typically must present your passport several times at the airport if you are flying, and at the border if you are travelling by car.

Is JWT obsolete? ›

In May 2023, Adobe announced the deprecation and end of life of Service Account (JWT) credentials. This means that any of your integrations or custom applications using a Service Account (JWT) credential will need to migrate to the new OAuth Server-to-Server credential before January 27, 2025.

What is the safest JWT algorithm? ›

To avoid these security vulnerabilities, it is crucial to follow good coding practices when working with JWT authentication: Always sign the JWT token: Use a secure signing algorithm, such as HMAC or RSA, to sign the token with a secret or private key. This ensures the integrity and authenticity of the token.

Is there something better than JWT? ›

I have recently read a few articles about PASETO, suggesting it is a better and more secure alternative to JWT.

What is the point of a JWT claim? ›

JWT claims are the core information that JWTs transmit (kinda like the letter inside a sealed envelope). The JWT claims included in the payload determine which information the JWT communicates (i.e., user identity, permissions, expiration of JWT, to name a few).

What is Passport for authentication? ›

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

What are the benefits of using a JWT? ›

Stateless Authentication: JWTs are self-contained and carry all the necessary information, which eliminates the need for a server-side session store. Scalability: Being stateless, JWTs are easily scalable across multiple servers as there's no need to share session data.

What is the purpose of JWT signature? ›

JWS signature: used to validate that the token is trustworthy and has not been tampered with. When you use a JWT, you must check its signature before storing and using it.

Top Articles
Why Solidity should not be your first language?
How Many Times Can a Creditor Place a Levy on My Bank Account?
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5998

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.