passport-jwt vs express-jwt vs express-jwt-authz vs express-jwt-permissions vs jsonwebtoken
JWT Authentication Middleware for Node.js
passport-jwtexpress-jwtexpress-jwt-authzexpress-jwt-permissionsjsonwebtokenSimilar Packages:
JWT Authentication Middleware for Node.js

These packages provide various functionalities for handling JSON Web Tokens (JWT) in Node.js applications, particularly for securing routes and managing user authentication. They help developers implement authentication strategies that protect APIs and manage permissions effectively. Each package has its unique features and use cases, making it essential to understand their differences to choose the right one for your application.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
passport-jwt2,082,3291,98252 kB41-MIT
express-jwt613,2704,51528.5 kB64a year agoMIT
express-jwt-authz38,584997.75 kB6-MIT
express-jwt-permissions16,78652219.9 kB9-MIT
jsonwebtoken018,11843.4 kB1855 days agoMIT
Feature Comparison: passport-jwt vs express-jwt vs express-jwt-authz vs express-jwt-permissions vs jsonwebtoken

Token Validation

  • passport-jwt:

    passport-jwt integrates token validation into the Passport authentication flow, allowing you to validate JWTs as part of a broader authentication strategy, making it easier to manage user sessions.

  • express-jwt:

    express-jwt provides a simple middleware to validate JWTs in incoming requests. It checks the token's signature and expiration, ensuring that only valid tokens can access protected routes.

  • express-jwt-authz:

    While express-jwt-authz builds on express-jwt, it focuses more on authorization rather than just validation. It ensures that the user has the necessary permissions based on the claims in the JWT after validation is done.

  • express-jwt-permissions:

    express-jwt-permissions offers a more detailed approach to permission checks after validating the token. It allows you to define and check specific permissions, making it suitable for applications with complex access control requirements.

  • jsonwebtoken:

    jsonwebtoken does not handle validation directly in the middleware context but provides functions to verify tokens and check their validity. It is essential for creating and managing JWTs but does not integrate as middleware.

Authorization Capabilities

  • passport-jwt:

    passport-jwt does not directly handle authorization; it focuses on validating the JWT as part of the Passport strategy. You will need to implement authorization checks based on the authenticated user.

  • express-jwt:

    express-jwt does not provide built-in authorization capabilities; it focuses solely on token validation. You will need to implement your own authorization logic after validation.

  • express-jwt-authz:

    express-jwt-authz adds authorization capabilities to express-jwt, allowing you to check user roles and permissions directly based on the claims in the JWT, making it easier to manage access control.

  • express-jwt-permissions:

    express-jwt-permissions allows for fine-grained permission checks, enabling you to define specific permissions that users must have to access certain routes, which is ideal for complex applications.

  • jsonwebtoken:

    jsonwebtoken does not provide authorization capabilities; it is primarily focused on token creation and verification. You will need to implement authorization logic separately.

Ease of Use

  • passport-jwt:

    passport-jwt is easy to use if you are already using Passport.js. It integrates seamlessly into the Passport authentication flow, but may require more setup if you are new to Passport.

  • express-jwt:

    express-jwt is easy to use and integrate into existing Express applications. It requires minimal setup and provides clear error handling for invalid tokens.

  • express-jwt-authz:

    express-jwt-authz is also straightforward to use, especially if you are already familiar with express-jwt. It extends the functionality without adding significant complexity.

  • express-jwt-permissions:

    express-jwt-permissions may require more initial setup to define permissions, but it provides a powerful way to manage access control once configured.

  • jsonwebtoken:

    jsonwebtoken is simple to use for creating and verifying tokens, but it requires additional code to integrate with Express middleware for validation.

Integration with Other Libraries

  • passport-jwt:

    passport-jwt is specifically designed to work with Passport.js, allowing for easy integration with other Passport strategies.

  • express-jwt:

    express-jwt integrates well with Express.js but does not have built-in support for other libraries or frameworks.

  • express-jwt-authz:

    express-jwt-authz is designed to work with express-jwt, making it a natural choice for applications that need both validation and authorization.

  • express-jwt-permissions:

    express-jwt-permissions can be used alongside express-jwt or express-jwt-authz, providing flexibility in how you manage permissions and access control.

  • jsonwebtoken:

    jsonwebtoken is a standalone library that can be used with any framework or library, but it requires additional code to integrate with Express.

Community and Support

  • passport-jwt:

    passport-jwt benefits from the extensive Passport.js community, providing a wealth of resources and support for developers.

  • express-jwt:

    express-jwt has a strong community and is widely used in the Node.js ecosystem, ensuring good support and regular updates.

  • express-jwt-authz:

    express-jwt-authz is less widely used than express-jwt but still has a supportive community, especially among those implementing role-based access control.

  • express-jwt-permissions:

    express-jwt-permissions has a smaller community, but it is gaining traction for applications requiring detailed permission management.

  • jsonwebtoken:

    jsonwebtoken has a large user base and is well-documented, making it easy to find support and examples for implementation.

How to Choose: passport-jwt vs express-jwt vs express-jwt-authz vs express-jwt-permissions vs jsonwebtoken
  • passport-jwt:

    Choose passport-jwt if you are already using Passport.js for authentication in your application. This strategy integrates JWT authentication into the Passport framework, allowing you to leverage Passport's extensive ecosystem for managing user authentication.

  • express-jwt:

    Choose express-jwt if you need a straightforward middleware for validating JWTs in your Express.js applications. It is suitable for applications that require basic token validation without additional authorization logic.

  • express-jwt-authz:

    Opt for express-jwt-authz if you need to implement role-based access control (RBAC) in your application. This package extends express-jwt by adding authorization capabilities based on the claims in the JWT, making it ideal for applications with complex permission requirements.

  • express-jwt-permissions:

    Select express-jwt-permissions if your application requires a more flexible and granular permission management system. This package allows you to define permissions based on the claims in the JWT and provides a simple way to check for specific permissions in your routes.

  • jsonwebtoken:

    Use jsonwebtoken if you need to create, sign, and verify JWTs manually. This package is essential for generating tokens and handling token expiration, making it a core component for any application that implements JWT-based authentication.

README for passport-jwt

passport-jwt

Build Status Code Climate

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.

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 Auth0 Logo

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 is extracted 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's signature. 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 only parameter and returns either the JWT as a string or null. See Extracting the JWT from the request for more details.
  • issuer: If defined the token issuer (iss) will be verified against this value.
  • audience: If defined, the token audience (aud) will be verified against this 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 verify callback. 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 arguments done(error, user, info)

An example configuration which reads the JWT from the http Authorization 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 as possible the JWT is parsed from the request by a user-supplied callback passed in as the jwtFromRequest 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 factory functions return a new extractor configured with the given parameters.

  • fromHeader(header_name) creates a new extractor that looks for the JWT in the given http header
  • fromBodyField(field_name) creates a new extractor that looks for the JWT in the given body field. 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 given URL query parameter.
  • fromAuthHeaderWithScheme(auth_scheme) creates a new extractor that looks for the JWT in the authorization header, expecting the scheme to match auth_scheme.
  • fromAuthHeaderAsBearerToken() creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'
  • fromExtractors([array of extractor functions]) creates a new extractor using an array of extractors 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. For example, if you are using the cookie-parser middleware and want to extract the JWT in a cookie you 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 extractor function you choose. For example, if you use the fromAuthHeaderAsBearerToken extractor, you would include an Authorization header in your request with the scheme set to bearer. e.g.

Authorization: bearer JSON_WEB_TOKEN_STRING.....

Migrating

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

Tests

npm install
npm test

To generate test-coverage reports:

npm install -g istanbul
npm run-script testcov
istanbul report

License

The MIT License

Copyright (c) 2015 Mike Nicholson