You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
15 KiB

4 years ago
  1. # jsonwebtoken
  2. | **Build** | **Dependency** |
  3. |-----------|---------------|
  4. | [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) |
  5. An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519).
  6. This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws)
  7. # Install
  8. ```bash
  9. $ npm install jsonwebtoken
  10. ```
  11. # Migration notes
  12. * [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8)
  13. # Usage
  14. ### jwt.sign(payload, secretOrPrivateKey, [options, callback])
  15. (Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT.
  16. (Synchronous) Returns the JsonWebToken as string
  17. `payload` could be an object literal, buffer or string representing valid JSON.
  18. > **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.
  19. > If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`.
  20. `secretOrPrivateKey` is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM
  21. encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option.
  22. `options`:
  23. * `algorithm` (default: `HS256`)
  24. * `expiresIn`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
  25. > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
  26. * `notBefore`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
  27. > Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
  28. * `audience`
  29. * `issuer`
  30. * `jwtid`
  31. * `subject`
  32. * `noTimestamp`
  33. * `header`
  34. * `keyid`
  35. * `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
  36. > There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places.
  37. Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim)
  38. The header can be customized via the `options.header` object.
  39. Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`.
  40. Synchronous Sign with default (HMAC SHA256)
  41. ```js
  42. var jwt = require('jsonwebtoken');
  43. var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
  44. ```
  45. Synchronous Sign with RSA SHA256
  46. ```js
  47. // sign with RSA SHA256
  48. var privateKey = fs.readFileSync('private.key');
  49. var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'});
  50. ```
  51. Sign asynchronously
  52. ```js
  53. jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
  54. console.log(token);
  55. });
  56. ```
  57. Backdate a jwt 30 seconds
  58. ```js
  59. var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
  60. ```
  61. #### Token Expiration (exp claim)
  62. The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**:
  63. > A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
  64. This means that the `exp` field should contain the number of seconds since the epoch.
  65. Signing a token with 1 hour of expiration:
  66. ```javascript
  67. jwt.sign({
  68. exp: Math.floor(Date.now() / 1000) + (60 * 60),
  69. data: 'foobar'
  70. }, 'secret');
  71. ```
  72. Another way to generate a token like this with this library is:
  73. ```javascript
  74. jwt.sign({
  75. data: 'foobar'
  76. }, 'secret', { expiresIn: 60 * 60 });
  77. //or even better:
  78. jwt.sign({
  79. data: 'foobar'
  80. }, 'secret', { expiresIn: '1h' });
  81. ```
  82. ### jwt.verify(token, secretOrPublicKey, [options, callback])
  83. (Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
  84. (Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
  85. `token` is the JsonWebToken string
  86. `secretOrPublicKey` is a string or buffer containing either the secret for HMAC algorithms, or the PEM
  87. encoded public key for RSA and ECDSA.
  88. If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example
  89. As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.
  90. `options`
  91. * `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`.
  92. * `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.
  93. > Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]`
  94. * `complete`: return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload.
  95. * `issuer` (optional): string or array of strings of valid values for the `iss` field.
  96. * `ignoreExpiration`: if `true` do not validate the expiration of the token.
  97. * `ignoreNotBefore`...
  98. * `subject`: if you want to check subject (`sub`), provide a value here
  99. * `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers
  100. * `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
  101. > Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
  102. * `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons.
  103. * `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes))
  104. ```js
  105. // verify a token symmetric - synchronous
  106. var decoded = jwt.verify(token, 'shhhhh');
  107. console.log(decoded.foo) // bar
  108. // verify a token symmetric
  109. jwt.verify(token, 'shhhhh', function(err, decoded) {
  110. console.log(decoded.foo) // bar
  111. });
  112. // invalid token - synchronous
  113. try {
  114. var decoded = jwt.verify(token, 'wrong-secret');
  115. } catch(err) {
  116. // err
  117. }
  118. // invalid token
  119. jwt.verify(token, 'wrong-secret', function(err, decoded) {
  120. // err
  121. // decoded undefined
  122. });
  123. // verify a token asymmetric
  124. var cert = fs.readFileSync('public.pem'); // get public key
  125. jwt.verify(token, cert, function(err, decoded) {
  126. console.log(decoded.foo) // bar
  127. });
  128. // verify audience
  129. var cert = fs.readFileSync('public.pem'); // get public key
  130. jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
  131. // if audience mismatch, err == invalid audience
  132. });
  133. // verify issuer
  134. var cert = fs.readFileSync('public.pem'); // get public key
  135. jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
  136. // if issuer mismatch, err == invalid issuer
  137. });
  138. // verify jwt id
  139. var cert = fs.readFileSync('public.pem'); // get public key
  140. jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
  141. // if jwt id mismatch, err == invalid jwt id
  142. });
  143. // verify subject
  144. var cert = fs.readFileSync('public.pem'); // get public key
  145. jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
  146. // if subject mismatch, err == invalid subject
  147. });
  148. // alg mismatch
  149. var cert = fs.readFileSync('public.pem'); // get public key
  150. jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
  151. // if token alg != RS256, err == invalid signature
  152. });
  153. // Verify using getKey callback
  154. // Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
  155. var jwksClient = require('jwks-rsa');
  156. var client = jwksClient({
  157. jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
  158. });
  159. function getKey(header, callback){
  160. client.getSigningKey(header.kid, function(err, key) {
  161. var signingKey = key.publicKey || key.rsaPublicKey;
  162. callback(null, signingKey);
  163. });
  164. }
  165. jwt.verify(token, getKey, options, function(err, decoded) {
  166. console.log(decoded.foo) // bar
  167. });
  168. ```
  169. ### jwt.decode(token [, options])
  170. (Synchronous) Returns the decoded payload without verifying if the signature is valid.
  171. > __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead.
  172. `token` is the JsonWebToken string
  173. `options`:
  174. * `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`.
  175. * `complete`: return an object with the decoded payload and header.
  176. Example
  177. ```js
  178. // get the decoded payload ignoring signature, no secretOrPrivateKey needed
  179. var decoded = jwt.decode(token);
  180. // get the decoded payload and header
  181. var decoded = jwt.decode(token, {complete: true});
  182. console.log(decoded.header);
  183. console.log(decoded.payload)
  184. ```
  185. ## Errors & Codes
  186. Possible thrown errors during verification.
  187. Error is the first argument of the verification callback.
  188. ### TokenExpiredError
  189. Thrown error if the token is expired.
  190. Error object:
  191. * name: 'TokenExpiredError'
  192. * message: 'jwt expired'
  193. * expiredAt: [ExpDate]
  194. ```js
  195. jwt.verify(token, 'shhhhh', function(err, decoded) {
  196. if (err) {
  197. /*
  198. err = {
  199. name: 'TokenExpiredError',
  200. message: 'jwt expired',
  201. expiredAt: 1408621000
  202. }
  203. */
  204. }
  205. });
  206. ```
  207. ### JsonWebTokenError
  208. Error object:
  209. * name: 'JsonWebTokenError'
  210. * message:
  211. * 'jwt malformed'
  212. * 'jwt signature is required'
  213. * 'invalid signature'
  214. * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
  215. * 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
  216. * 'jwt id invalid. expected: [OPTIONS JWT ID]'
  217. * 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
  218. ```js
  219. jwt.verify(token, 'shhhhh', function(err, decoded) {
  220. if (err) {
  221. /*
  222. err = {
  223. name: 'JsonWebTokenError',
  224. message: 'jwt malformed'
  225. }
  226. */
  227. }
  228. });
  229. ```
  230. ### NotBeforeError
  231. Thrown if current time is before the nbf claim.
  232. Error object:
  233. * name: 'NotBeforeError'
  234. * message: 'jwt not active'
  235. * date: 2018-10-04T16:10:44.000Z
  236. ```js
  237. jwt.verify(token, 'shhhhh', function(err, decoded) {
  238. if (err) {
  239. /*
  240. err = {
  241. name: 'NotBeforeError',
  242. message: 'jwt not active',
  243. date: 2018-10-04T16:10:44.000Z
  244. }
  245. */
  246. }
  247. });
  248. ```
  249. ## Algorithms supported
  250. Array of supported algorithms. The following algorithms are currently supported.
  251. alg Parameter Value | Digital Signature or MAC Algorithm
  252. ----------------|----------------------------
  253. HS256 | HMAC using SHA-256 hash algorithm
  254. HS384 | HMAC using SHA-384 hash algorithm
  255. HS512 | HMAC using SHA-512 hash algorithm
  256. RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm
  257. RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm
  258. RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm
  259. PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0)
  260. PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0)
  261. PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0)
  262. ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
  263. ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
  264. ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
  265. none | No digital signature or MAC value included
  266. ## Refreshing JWTs
  267. First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.
  268. We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished.
  269. Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic.
  270. # TODO
  271. * X.509 certificate chain is not checked
  272. ## Issue Reporting
  273. 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.
  274. ## Author
  275. [Auth0](https://auth0.com)
  276. ## License
  277. This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.