1 | # express-jwt
|
2 |
|
3 | This 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 |
|
13 | Basic usage using an HS256 secret:
|
14 |
|
15 | ```javascript
|
16 | var { expressjwt: jwt } = require("express-jwt");
|
17 | // or ES6
|
18 | // import { expressjwt, ExpressJwtRequest } from "express-jwt";
|
19 |
|
20 | app.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 |
|
30 | The 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 |
|
36 | The `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
|
41 | jwt({
|
42 | secret: "shhhhhhared-secret",
|
43 | algorithms: ["HS256"],
|
44 | //algorithms: ['RS256']
|
45 | });
|
46 | ```
|
47 |
|
48 | ### Additional Options
|
49 |
|
50 | You can specify audience and/or issuer as well, which is highly recommended for security purposes:
|
51 |
|
52 | ```javascript
|
53 | jwt({
|
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 |
|
63 | If you are using a base64 URL-encoded secret, pass a `Buffer` with `base64` encoding as the secret instead of a string:
|
64 |
|
65 | ```javascript
|
66 | jwt({
|
67 | secret: Buffer.from("shhhhhhared-secret", "base64"),
|
68 | algorithms: ["RS256"],
|
69 | });
|
70 | ```
|
71 |
|
72 | To 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
|
75 | app.use("/api", jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }));
|
76 | ```
|
77 |
|
78 | Or, the other way around, if you want to make some paths unprotected, cal `unless` like so.
|
79 |
|
80 | ```javascript
|
81 | app.use(
|
82 | jwt({
|
83 | secret: "shhhhhhared-secret",
|
84 | algorithms: ["HS256"],
|
85 | }).unless({ path: ["/token"] })
|
86 | );
|
87 | ```
|
88 |
|
89 | 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.
|
90 |
|
91 | > For more details on the `.unless` syntax including additional options, please see [express-unless](https://github.com/jfromaniello/express-unless).
|
92 |
|
93 | This 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
|
96 | var publicKey = fs.readFileSync("/path/to/public.pub");
|
97 | jwt({ secret: publicKey, algorithms: ["RS256"] });
|
98 | ```
|
99 |
|
100 | ### Customizing Token Location
|
101 |
|
102 | A custom function for extracting the token from a request can be specified with
|
103 | the `getToken` option. This is useful if you need to pass the token through a
|
104 | query parameter or a cookie. You can throw an error in this function and it will
|
105 | be handled by `express-jwt`.
|
106 |
|
107 | ```javascript
|
108 | app.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 | ### Retrieve key dynamically
|
129 |
|
130 | If you need to obtain the key dynamically from other sources, you can pass a function in the `secret` parameter with the following parameters:
|
131 |
|
132 | - `req` (`Object`) - The express `request` object.
|
133 | - `token` (`Object`) - An object with the JWT payload and headers.
|
134 |
|
135 | For example, if the secret varies based on the [issuer](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#issDef):
|
136 |
|
137 | ```javascript
|
138 | var jwt = require("express-jwt");
|
139 | var data = require("./data");
|
140 | var utilities = require("./utilities");
|
141 |
|
142 | var 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 |
|
151 | app.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 |
|
163 | 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)`:
|
164 |
|
165 | - `req` (`Object`) - The express `request` object.
|
166 | - `token` (`Object`) - An object with the JWT payload and headers.
|
167 |
|
168 | For example, if the `(iss, jti)` claim pair is used to identify a JWT:
|
169 |
|
170 | ```javascript
|
171 | const jwt = require("express-jwt");
|
172 | const data = require("./data");
|
173 |
|
174 | const 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 |
|
181 | app.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 |
|
197 | 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:
|
198 |
|
199 | ```javascript
|
200 | app.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 |
|
209 | You 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
|
212 | app.use(
|
213 | jwt({
|
214 | secret: "hello world !",
|
215 | algorithms: ["HS256"],
|
216 | credentialsRequired: false,
|
217 | })
|
218 | );
|
219 | ```
|
220 |
|
221 | ## Typescript
|
222 |
|
223 | An `ExpressJwtRequest` type is provided which extends `express.Request` with the `auth` property.
|
224 |
|
225 | ```typescript
|
226 | import { expressjwt, ExpressJwtRequest } from "express-jwt";
|
227 |
|
228 | app.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 |
|
252 | Check them out [here](https://github.com/auth0/express-jwt/graphs/contributors)
|
253 |
|
254 | ## Issue Reporting
|
255 |
|
256 | 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.
|
257 |
|
258 | ## Author
|
259 |
|
260 | [Auth0](https://auth0.com)
|
261 |
|
262 | ## License
|
263 |
|
264 | This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
|