UNPKG

6.48 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.send(401);
30 res.send(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
44Optionally you can make some paths unprotected as follows:
45
46```javascript
47app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));
48```
49
50This 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.
51
52> For more details on the `.unless` syntax including additional options, please see [express-unless](https://github.com/jfromaniello/express-unless).
53
54This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key
55
56```javascript
57var publicKey = fs.readFileSync('/pat/to/public.pub');
58jwt({ secret: publicKey });
59```
60
61By default, the decoded token is attached to `req.user` but can be configured with the `requestProperty` option.
62
63```javascript
64jwt({ secret: publicKey, requestProperty: 'auth' });
65```
66
67A custom function for extracting the token from a request can be specified with
68the `getToken` option. This is useful if you need to pass the token through a
69query parameter or a cookie. You can throw an error in this function and it will
70be handled by `express-jwt`.
71
72```javascript
73app.use(jwt({
74 secret: 'hello world !',
75 credentialsRequired: false,
76 getToken: function fromHeaderOrQuerystring (req) {
77 if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
78 return req.headers.authorization.split(' ')[1];
79 } else if (req.query && req.query.token) {
80 return req.query.token;
81 }
82 return null;
83 }
84}));
85```
86
87### Multi-tenancy
88If 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)`:
89* `req` (`Object`) - The express `request` object.
90* `payload` (`Object`) - An object with the JWT claims.
91* `done` (`Function`) - A function with signature `function(err, secret)` to be invoked when the secret is retrieved.
92 * `err` (`Any`) - The error that occurred.
93 * `secret` (`String`) - The secret to use to verify the JWT.
94
95For example, if the secret varies based on the [JWT issuer](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#issDef):
96```javascript
97var jwt = require('express-jwt');
98var data = require('./data');
99var utilities = require('./utilities');
100
101var secretCallback = function(req, payload, done){
102 var issuer = payload.iss;
103
104 data.getTenantByIdentifier(issuer, function(err, tenant){
105 if (err) { return done(err); }
106 if (!tenant) { return done(new Error('missing_secret')); }
107
108 var secret = utilities.decrypt(tenant.secret);
109 done(null, secret);
110 });
111};
112
113app.get('/protected',
114 jwt({secret: secretCallback}),
115 function(req, res) {
116 if (!req.user.admin) return res.send(401);
117 res.send(200);
118 });
119```
120
121### Revoked tokens
122It 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)`:
123* `req` (`Object`) - The express `request` object.
124* `payload` (`Object`) - An object with the JWT claims.
125* `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.
126 * `err` (`Any`) - The error that occurred.
127 * `revoked` (`Boolean`) - `true` if the JWT is revoked, `false` otherwise.
128
129For example, if the `(iss, jti)` claim pair is used to identify a JWT:
130```javascript
131var jwt = require('express-jwt');
132var data = require('./data');
133var utilities = require('./utilities');
134
135var isRevokedCallback = function(req, payload, done){
136 var issuer = payload.iss;
137 var tokenId = payload.jti;
138
139 data.getRevokedToken(issuer, tokenId, function(err, token){
140 if (err) { return done(err); }
141 return done(null, !!token);
142 });
143};
144
145app.get('/protected',
146 jwt({secret: shhhhhhared-secret,
147 isRevoked: isRevokedCallback}),
148 function(req, res) {
149 if (!req.user.admin) return res.send(401);
150 res.send(200);
151 });
152```
153
154### Error handling
155
156The 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:
157
158
159```javascript
160app.use(function (err, req, res, next) {
161 if (err.name === 'UnauthorizedError') {
162 res.send(401, 'invalid token...');
163 }
164});
165```
166
167You might want to use this module to identify registered users without preventing unregistered clients to access to some data, you
168can do it using the option _credentialsRequired_:
169
170 app.use(jwt({
171 secret: 'hello world !',
172 credentialsRequired: false
173 }));
174
175## Related Modules
176
177- [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) — JSON Web Token sign and verification
178
179## Issue Reporting
180
181If 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.
182
183## Tests
184
185 $ npm install
186 $ npm test
187
188## Contributors
189Check them out [here](https://github.com/auth0/express-jwt/graphs/contributors)
190
191## License
192
193This project is licensed under the MIT license. See the [LICENSE](LICENSE.txt) file for more info.