UNPKG

7.73 kBMarkdownView Raw
1# express-jwt
2
3This module provides Express middleware for validating JWTs ([JSON Web Tokens](https://jwt.io)) through the [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken/) module. The decoded JWT payload is available on the request object.
4
5## Install
6
7```
8$ npm install express-jwt
9```
10
11## Usage
12
13Basic usage using an HS256 secret:
14
15```javascript
16var { expressjwt: jwt } = require("express-jwt");
17// or ES6
18// import { expressjwt, ExpressJwtRequest } from "express-jwt";
19
20app.get(
21 "/protected",
22 jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
23 function (req, res) {
24 if (!req.auth.admin) return res.sendStatus(401);
25 res.sendStatus(200);
26 }
27);
28```
29
30The decoded JWT payload is available on the request via the `auth` property.
31
32> The default behavior of the module is to extract the JWT from the `Authorization` header as an [OAuth2 Bearer token](https://oauth.net/2/bearer-tokens/).
33
34### Required Parameters
35
36The `algorithms` parameter is required to prevent potential downgrade attacks when providing third party libraries as **secrets**.
37
38:warning: **Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms**: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.
39
40```javascript
41jwt({
42 secret: "shhhhhhared-secret",
43 algorithms: ["HS256"],
44 //algorithms: ['RS256']
45});
46```
47
48### Additional Options
49
50You can specify audience and/or issuer as well, which is highly recommended for security purposes:
51
52```javascript
53jwt({
54 secret: "shhhhhhared-secret",
55 audience: "http://myapi/protected",
56 issuer: "http://issuer",
57 algorithms: ["HS256"],
58});
59```
60
61> If the JWT has an expiration (`exp`), it will be checked.
62
63If you are using a base64 URL-encoded secret, pass a `Buffer` with `base64` encoding as the secret instead of a string:
64
65```javascript
66jwt({
67 secret: Buffer.from("shhhhhhared-secret", "base64"),
68 algorithms: ["RS256"],
69});
70```
71
72To only protect specific paths (e.g. beginning with `/api`), use [express router](https://expressjs.com/en/4x/api.html#app.use) call `use`, like so:
73
74```javascript
75app.use("/api", jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }));
76```
77
78Or, the other way around, if you want to make some paths unprotected, cal `unless` like so.
79
80```javascript
81app.use(
82 jwt({
83 secret: "shhhhhhared-secret",
84 algorithms: ["HS256"],
85 }).unless({ path: ["/token"] })
86);
87```
88
89This 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.
90
91> For more details on the `.unless` syntax including additional options, please see [express-unless](https://github.com/jfromaniello/express-unless).
92
93This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key
94
95```javascript
96var publicKey = fs.readFileSync("/path/to/public.pub");
97jwt({ secret: publicKey, algorithms: ["RS256"] });
98```
99
100### Customizing Token Location
101
102A custom function for extracting the token from a request can be specified with
103the `getToken` option. This is useful if you need to pass the token through a
104query parameter or a cookie. You can throw an error in this function and it will
105be handled by `express-jwt`.
106
107```javascript
108app.use(
109 jwt({
110 secret: "hello world !",
111 algorithms: ["HS256"],
112 credentialsRequired: false,
113 getToken: function fromHeaderOrQuerystring(req) {
114 if (
115 req.headers.authorization &&
116 req.headers.authorization.split(" ")[0] === "Bearer"
117 ) {
118 return req.headers.authorization.split(" ")[1];
119 } else if (req.query && req.query.token) {
120 return req.query.token;
121 }
122 return null;
123 },
124 })
125);
126```
127
128### Multi-tenancy
129
130If 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)`:
131
132- `req` (`Object`) - The express `request` object.
133- `token` (`Object`) - An object with the JWT payload and headers.
134
135For example, if the secret varies based on the [JWT issuer](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#issDef):
136
137```javascript
138var jwt = require("express-jwt");
139var data = require("./data");
140var utilities = require("./utilities");
141
142var getSecret = async function (req, token) {
143 const issuer = token.payload.iss;
144 const tenant = await data.getTenantByIdentifier(issuer);
145 if (!tenant) {
146 throw new Error("missing_secret");
147 }
148 return utilities.decrypt(tenant.secret);
149};
150
151app.get(
152 "/protected",
153 jwt({ secret: getSecret, algorithms: ["HS256"] }),
154 function (req, res) {
155 if (!req.auth.admin) return res.sendStatus(401);
156 res.sendStatus(200);
157 }
158);
159```
160
161### Revoked tokens
162
163It 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)`:
164
165- `req` (`Object`) - The express `request` object.
166- `token` (`Object`) - An object with the JWT payload and headers.
167
168For example, if the `(iss, jti)` claim pair is used to identify a JWT:
169
170```javascript
171const jwt = require("express-jwt");
172const data = require("./data");
173
174const isRevokedCallback = async (req, token) => {
175 const issuer = token.payload.iss;
176 const tokenId = token.payload.jti;
177 const token = await data.getRevokedToken(issuer, tokenId);
178 return token !== "undefined";
179};
180
181app.get(
182 "/protected",
183 jwt({
184 secret: "shhhhhhared-secret",
185 algorithms: ["HS256"],
186 isRevoked: isRevokedCallback,
187 }),
188 function (req, res) {
189 if (!req.auth.admin) return res.sendStatus(401);
190 res.sendStatus(200);
191 }
192);
193```
194
195### Error handling
196
197The 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:
198
199```javascript
200app.use(function (err, req, res, next) {
201 if (err.name === "UnauthorizedError") {
202 res.status(401).send("invalid token...");
203 } else {
204 next(err);
205 }
206});
207```
208
209You might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option `credentialsRequired`:
210
211```javascript
212app.use(
213 jwt({
214 secret: "hello world !",
215 algorithms: ["HS256"],
216 credentialsRequired: false,
217 })
218);
219```
220
221## Typescript
222
223An `ExpressJwtRequest` type is provided which extends `express.Request` with the `auth` property.
224
225```typescript
226import { expressjwt, ExpressJwtRequest } from "express-jwt";
227
228app.get(
229 "/protected",
230 expressjwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
231 function (req: ExpressJwtRequest, res: express.Response) {
232 if (!req.auth.admin) return res.sendStatus(401);
233 res.sendStatus(200);
234 }
235);
236```
237
238## Related Modules
239
240- [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) — JSON Web Token sign and verification
241- [express-jwt-permissions](https://github.com/MichielDeMey/express-jwt-permissions) - Permissions middleware for JWT tokens
242
243## Tests
244
245```
246$ npm install
247$ npm test
248```
249
250## Contributors
251
252Check them out [here](https://github.com/auth0/express-jwt/graphs/contributors)
253
254## Issue Reporting
255
256If 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.
257
258## Author
259
260[Auth0](https://auth0.com)
261
262## License
263
264This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.