1 | # express-jwt
|
2 |
|
3 | [![Build](https://travis-ci.org/auth0/express-jwt.png)](http://travis-ci.org/auth0/express-jwt)
|
4 |
|
5 | Middleware that validates JsonWebTokens and sets `req.user`.
|
6 |
|
7 | This module lets you authenticate HTTP requests using JWT tokens in your Node.js
|
8 | applications. JWTs are typically used to protect API endpoints, and are
|
9 | often issued using OpenID Connect.
|
10 |
|
11 | ## Install
|
12 |
|
13 | $ npm install express-jwt
|
14 |
|
15 | ## Usage
|
16 |
|
17 | The JWT authentication middleware authenticates callers using a JWT.
|
18 | If the token is valid, `req.user` will be set with the JSON object decoded
|
19 | to be used by later middleware for authorization and access control.
|
20 |
|
21 | For example,
|
22 |
|
23 | ```javascript
|
24 | var jwt = require('express-jwt');
|
25 |
|
26 | app.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 |
|
34 | You can specify audience and/or issuer as well:
|
35 |
|
36 | ```javascript
|
37 | jwt({ 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 |
|
44 | If you are using a base64 URL-encoded secret, pass a `Buffer` with `base64` encoding as the secret instead of a string:
|
45 |
|
46 | ```javascript
|
47 | jwt({ secret: new Buffer('shhhhhhared-secret', 'base64') })
|
48 | ```
|
49 |
|
50 | Optionally you can make some paths unprotected as follows:
|
51 |
|
52 | ```javascript
|
53 | app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));
|
54 | ```
|
55 |
|
56 | This 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 |
|
60 | This 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
|
63 | var publicKey = fs.readFileSync('/pat/to/public.pub');
|
64 | jwt({ secret: publicKey });
|
65 | ```
|
66 |
|
67 | By default, the decoded token is attached to `req.user` but can be configured with the `requestProperty` option.
|
68 |
|
69 |
|
70 | ```javascript
|
71 | jwt({ secret: publicKey, requestProperty: 'auth' });
|
72 | ```
|
73 |
|
74 | A custom function for extracting the token from a request can be specified with
|
75 | the `getToken` option. This is useful if you need to pass the token through a
|
76 | query parameter or a cookie. You can throw an error in this function and it will
|
77 | be handled by `express-jwt`.
|
78 |
|
79 | ```javascript
|
80 | app.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
|
95 | If 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 |
|
102 | For 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
|
104 | var jwt = require('express-jwt');
|
105 | var data = require('./data');
|
106 | var utilities = require('./utilities');
|
107 |
|
108 | var 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 |
|
120 | app.get('/protected',
|
121 | jwt({secret: secretCallback}),
|
122 | function(req, res) {
|
123 | if (!req.user.admin) return res.send(401);
|
124 | res.send(200);
|
125 | });
|
126 | ```
|
127 |
|
128 | ### Revoked tokens
|
129 | It 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 |
|
136 | For example, if the `(iss, jti)` claim pair is used to identify a JWT:
|
137 | ```javascript
|
138 | var jwt = require('express-jwt');
|
139 | var data = require('./data');
|
140 | var utilities = require('./utilities');
|
141 |
|
142 | var 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 |
|
152 | app.get('/protected',
|
153 | jwt({secret: shhhhhhared-secret,
|
154 | isRevoked: isRevokedCallback}),
|
155 | function(req, res) {
|
156 | if (!req.user.admin) return res.send(401);
|
157 | res.send(200);
|
158 | });
|
159 | ```
|
160 |
|
161 | ### Error handling
|
162 |
|
163 | The 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
|
167 | app.use(function (err, req, res, next) {
|
168 | if (err.name === 'UnauthorizedError') {
|
169 | res.send(401, 'invalid token...');
|
170 | }
|
171 | });
|
172 | ```
|
173 |
|
174 | You might want to use this module to identify registered users while still providing access to unregistered users. You
|
175 | can 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 |
|
186 | ## Issue Reporting
|
187 |
|
188 | If 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.
|
189 |
|
190 | ## Tests
|
191 |
|
192 | $ npm install
|
193 | $ npm test
|
194 |
|
195 | ## Contributors
|
196 | Check them out [here](https://github.com/auth0/express-jwt/graphs/contributors)
|
197 |
|
198 | ## License
|
199 |
|
200 | This project is licensed under the MIT license. See the [LICENSE](LICENSE.txt) file for more info.
|