thoughts/node_modules/jsonwebtoken/README.md
node_modules/jsonwebtoken/README.mdRaw
1# jsonwebtoken [](http://travis-ci.org/auth0/node-jsonwebtoken)[](https://david-dm.org/auth0/node-jsonwebtoken)
2
3
4An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519).
5
6This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws)
7
8# Install
9
10```bash
11$ npm install jsonwebtoken
12```
13
14# Usage
15
16### jwt.sign(payload, secretOrPrivateKey, options, [callback])
17
18(Asynchronous) If a callback is supplied, callback is called with the `err` or the JWT.
19
20(Synchronous) Returns the JsonWebToken as string
21
22`payload` could be an object literal, buffer or string. *Please note that* `exp` is only set if the payload is an object literal.
23
24`secretOrPrivateKey` is a string or buffer containing either the secret for HMAC algorithms, or the PEM
25encoded private key for RSA and ECDSA.
26
27`options`:
28
29* `algorithm` (default: `HS256`)
30* `expiresIn`: expressed in seconds or a string describing a time span [rauchg/ms](https://github.com/rauchg/ms.js). Eg: `60`, `"2 days"`, `"10h"`, `"7d"`
31* `notBefore`: expressed in seconds or a string describing a time span [rauchg/ms](https://github.com/rauchg/ms.js). Eg: `60`, `"2 days"`, `"10h"`, `"7d"`
32* `audience`
33* `issuer`
34* `jwtid`
35* `subject`
36* `noTimestamp`
37* `header`
38
39If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`.
40
41There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud` and `sub` respectively, but you can't include in both places.
42
43
44The header can be customized via the `option.header` object.
45
46Generated 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`.
47
48Example
49
50```js
51// sign with default (HMAC SHA256)
52var jwt = require('jsonwebtoken');
53var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
54//backdate a jwt 30 seconds
55var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
56
57// sign with RSA SHA256
58var cert = fs.readFileSync('private.key'); // get private key
59var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});
60
61// sign asynchronously
62jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
63 console.log(token);
64});
65```
66
67### jwt.verify(token, secretOrPublicKey, [options, callback])
68
69(Asynchronous) If a callback is supplied, function acts asynchronously. Callback passed the payload decoded if the signature (and optionally expiration, audience, issuer) are valid. If not, it will be passed the error.
70
71(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature (and optionally expiration, audience, issuer) are valid. If not, it will throw the error.
72
73`token` is the JsonWebToken string
74
75`secretOrPublicKey` is a string or buffer containing either the secret for HMAC algorithms, or the PEM
76encoded public key for RSA and ECDSA.
77
78`options`
79
80* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`.
81* `audience`: if you want to check audience (`aud`), provide a value here
82* `issuer` (optional): string or array of strings of valid values for the `iss` field.
83* `ignoreExpiration`: if `true` do not validate the expiration of the token.
84* `ignoreNotBefore`...
85* `subject`: if you want to check subject (`sub`), provide a value here
86* `clockTolerance`: number of second to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers
87
88
89```js
90// verify a token symmetric - synchronous
91var decoded = jwt.verify(token, 'shhhhh');
92console.log(decoded.foo) // bar
93
94// verify a token symmetric
95jwt.verify(token, 'shhhhh', function(err, decoded) {
96 console.log(decoded.foo) // bar
97});
98
99// invalid token - synchronous
100try {
101 var decoded = jwt.verify(token, 'wrong-secret');
102} catch(err) {
103 // err
104}
105
106// invalid token
107jwt.verify(token, 'wrong-secret', function(err, decoded) {
108 // err
109 // decoded undefined
110});
111
112// verify a token asymmetric
113var cert = fs.readFileSync('public.pem'); // get public key
114jwt.verify(token, cert, function(err, decoded) {
115 console.log(decoded.foo) // bar
116});
117
118// verify audience
119var cert = fs.readFileSync('public.pem'); // get public key
120jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
121 // if audience mismatch, err == invalid audience
122});
123
124// verify issuer
125var cert = fs.readFileSync('public.pem'); // get public key
126jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
127 // if issuer mismatch, err == invalid issuer
128});
129
130// verify jwt id
131var cert = fs.readFileSync('public.pem'); // get public key
132jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
133 // if jwt id mismatch, err == invalid jwt id
134});
135
136// verify subject
137var cert = fs.readFileSync('public.pem'); // get public key
138jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
139 // if subject mismatch, err == invalid subject
140});
141
142// alg mismatch
143var cert = fs.readFileSync('public.pem'); // get public key
144jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
145 // if token alg != RS256, err == invalid signature
146});
147
148```
149
150### jwt.decode(token [, options])
151
152(Synchronous) Returns the decoded payload without verifying if the signature is valid.
153
154__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.
155
156`token` is the JsonWebToken string
157
158`options`:
159
160* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`.
161* `complete`: return an object with the decoded payload and header.
162
163Example
164
165```js
166// get the decoded payload ignoring signature, no secretOrPrivateKey needed
167var decoded = jwt.decode(token);
168
169// get the decoded payload and header
170var decoded = jwt.decode(token, {complete: true});
171console.log(decoded.header);
172console.log(decoded.payload)
173```
174
175## Errors & Codes
176Possible thrown errors during verification.
177Error is the first argument of the verification callback.
178
179### TokenExpiredError
180
181Thrown error if the token is expired.
182
183Error object:
184
185* name: 'TokenExpiredError'
186* message: 'jwt expired'
187* expiredAt: [ExpDate]
188
189```js
190jwt.verify(token, 'shhhhh', function(err, decoded) {
191 if (err) {
192 /*
193 err = {
194 name: 'TokenExpiredError',
195 message: 'jwt expired',
196 expiredAt: 1408621000
197 }
198 */
199 }
200});
201```
202
203### JsonWebTokenError
204Error object:
205
206* name: 'JsonWebTokenError'
207* message:
208 * 'jwt malformed'
209 * 'jwt signature is required'
210 * 'invalid signature'
211 * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
212 * 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
213 * 'jwt id invalid. expected: [OPTIONS JWT ID]'
214 * 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
215
216```js
217jwt.verify(token, 'shhhhh', function(err, decoded) {
218 if (err) {
219 /*
220 err = {
221 name: 'JsonWebTokenError',
222 message: 'jwt malformed'
223 }
224 */
225 }
226});
227```
228
229## Algorithms supported
230
231Array of supported algorithms. The following algorithms are currently supported.
232
233alg Parameter Value | Digital Signature or MAC Algorithm
234----------------|----------------------------
235HS256 | HMAC using SHA-256 hash algorithm
236HS384 | HMAC using SHA-384 hash algorithm
237HS512 | HMAC using SHA-512 hash algorithm
238RS256 | RSASSA using SHA-256 hash algorithm
239RS384 | RSASSA using SHA-384 hash algorithm
240RS512 | RSASSA using SHA-512 hash algorithm
241ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
242ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
243ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
244none | No digital signature or MAC value included
245
246# TODO
247
248* X.509 certificate chain is not checked
249
250## Issue Reporting
251
252If 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.
253
254## Author
255
256[Auth0](https://auth0.com)
257
258## License
259
260This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.