passport-jwt
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/developersInstall
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
secretOrKeyProvider
is provided.secretOrKeyProvider
is a callback in the formatfunction secretOrKeyProvider(request, rawJwtToken, done)
,
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
issuer
: If defined the token issuer (iss) will be verified against this
audience
: If defined, the token audience (aud) will be verified against
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
jsonWebTokenOptions
: passport-jwt is verifying the token using jsonwebtoken.
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
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 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 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
- ``
fromBodyField(field_name)
`` creates a new extractor that looks for the JWT in the given body
- ``
fromUrlQueryParameter(param_name)
`` creates a new extractor that looks for the JWT in the given
- ``
fromAuthHeaderWithScheme(auth_scheme)
`` creates a new extractor that looks for the JWT in the
- ``
fromAuthHeaderAsBearerToken()
`` creates a new extractor that looks for the JWT in the authorization header
- ``
fromExtractors([array of extractor functions])
`` creates a new extractor using an array of
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
Usepassport.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 thefromAuthHeaderAsBearerToken
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 LicenseCopyright (c) 2015 Mike Nicholson