UNPKG

6.87 kBMarkdownView Raw
1# express-jwt
2
3[![Build](https://travis-ci.org/auth0/express-jwt.png)](http://travis-ci.org/auth0/express-jwt)
4
5Middleware that validates JsonWebTokens and sets `req.user`.
6
7This module lets you authenticate HTTP requests using JWT tokens in your Node.js
8applications. JWTs are typically used to protect API endpoints, and are
9often issued using OpenID Connect.
10
11## Install
12
13 $ npm install express-jwt
14
15## Usage
16
17The JWT authentication middleware authenticates callers using a JWT.
18If the token is valid, `req.user` will be set with the JSON object decoded
19to be used by later middleware for authorization and access control.
20
21For example,
22
23```javascript
24var jwt = require('express-jwt');
25
26app.get('/protected',
27 jwt({secret: 'shhhhhhared-secret'}),
28 function(req, res) {
29 if (!req.user.admin) return res.sendStatus(401);
30 res.sendStatus(200);
31 });
32```
33
34You can specify audience and/or issuer as well:
35
36```javascript
37jwt({ secret: 'shhhhhhared-secret',
38 audience: 'http://myapi/protected',
39 issuer: 'http://issuer' })
40```
41
42> If the JWT has an expiration (`exp`), it will be checked.
43
44If you are using a base64 URL-encoded secret, pass a `Buffer` with `base64` encoding as the secret instead of a string:
45
46```javascript
47jwt({ secret: new Buffer('shhhhhhared-secret', 'base64') })
48```
49
50Optionally you can make some paths unprotected as follows:
51
52```javascript
53app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));
54```
55
56This is especially useful when applying to multiple routes. In the example above, `path` can be a string, a regexp, or an array of any of those.
57
58> For more details on the `.unless` syntax including additional options, please see [express-unless](https://github.com/jfromaniello/express-unless).
59
60This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key
61
62```javascript
63var publicKey = fs.readFileSync('/path/to/public.pub');
64jwt({ secret: publicKey });
65```
66
67By default, the decoded token is attached to `req.user` but can be configured with the `requestProperty` option.
68
69
70```javascript
71jwt({ secret: publicKey, requestProperty: 'auth' });
72```
73
74A custom function for extracting the token from a request can be specified with
75the `getToken` option. This is useful if you need to pass the token through a
76query parameter or a cookie. You can throw an error in this function and it will
77be handled by `express-jwt`.
78
79```javascript
80app.use(jwt({
81 secret: 'hello world !',
82 credentialsRequired: false,
83 getToken: function fromHeaderOrQuerystring (req) {
84 if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
85 return req.headers.authorization.split(' ')[1];
86 } else if (req.query && req.query.token) {
87 return req.query.token;
88 }
89 return null;
90 }
91}));
92```
93
94### Multi-tenancy
95If you are developing an application in which the secret used to sign tokens is not static, you can provide a callback function as the `secret` parameter. The function has the signature: `function(req, payload, done)`:
96* `req` (`Object`) - The express `request` object.
97* `payload` (`Object`) - An object with the JWT claims.
98* `done` (`Function`) - A function with signature `function(err, secret)` to be invoked when the secret is retrieved.
99 * `err` (`Any`) - The error that occurred.
100 * `secret` (`String`) - The secret to use to verify the JWT.
101
102For example, if the secret varies based on the [JWT issuer](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#issDef):
103```javascript
104var jwt = require('express-jwt');
105var data = require('./data');
106var utilities = require('./utilities');
107
108var secretCallback = function(req, payload, done){
109 var issuer = payload.iss;
110
111 data.getTenantByIdentifier(issuer, function(err, tenant){
112 if (err) { return done(err); }
113 if (!tenant) { return done(new Error('missing_secret')); }
114
115 var secret = utilities.decrypt(tenant.secret);
116 done(null, secret);
117 });
118};
119
120app.get('/protected',
121 jwt({secret: secretCallback}),
122 function(req, res) {
123 if (!req.user.admin) return res.sendStatus(401);
124 res.sendStatus(200);
125 });
126```
127
128### Revoked tokens
129It is possible that some tokens will need to be revoked so they cannot be used any longer. You can provide a function as the `isRevoked` option. The signature of the function is `function(req, payload, done)`:
130* `req` (`Object`) - The express `request` object.
131* `payload` (`Object`) - An object with the JWT claims.
132* `done` (`Function`) - A function with signature `function(err, revoked)` to be invoked once the check to see if the token is revoked or not is complete.
133 * `err` (`Any`) - The error that occurred.
134 * `revoked` (`Boolean`) - `true` if the JWT is revoked, `false` otherwise.
135
136For example, if the `(iss, jti)` claim pair is used to identify a JWT:
137```javascript
138var jwt = require('express-jwt');
139var data = require('./data');
140var utilities = require('./utilities');
141
142var isRevokedCallback = function(req, payload, done){
143 var issuer = payload.iss;
144 var tokenId = payload.jti;
145
146 data.getRevokedToken(issuer, tokenId, function(err, token){
147 if (err) { return done(err); }
148 return done(null, !!token);
149 });
150};
151
152app.get('/protected',
153 jwt({secret: 'shhhhhhared-secret',
154 isRevoked: isRevokedCallback}),
155 function(req, res) {
156 if (!req.user.admin) return res.sendStatus(401);
157 res.sendStatus(200);
158 });
159```
160
161### Error handling
162
163The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:
164
165
166```javascript
167app.use(function (err, req, res, next) {
168 if (err.name === 'UnauthorizedError') {
169 res.status(401).send('invalid token...');
170 }
171});
172```
173
174You might want to use this module to identify registered users while still providing access to unregistered users. You
175can do this by using the option _credentialsRequired_:
176
177 app.use(jwt({
178 secret: 'hello world !',
179 credentialsRequired: false
180 }));
181
182## Related Modules
183
184- [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) — JSON Web Token sign and verification
185- [express-jwt-permissions](https://github.com/MichielDeMey/express-jwt-permissions) - Permissions middleware for JWT tokens
186
187## Tests
188
189 $ npm install
190 $ npm test
191
192## Contributors
193Check them out [here](https://github.com/auth0/express-jwt/graphs/contributors)
194
195## Issue Reporting
196
197If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
198
199## Author
200
201[Auth0](auth0.com)
202
203## License
204
205This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.