|
| 1 | +# Web JWT |
| 2 | + |
| 3 | +[![NPM version][npm-image]][npm-url] |
| 4 | +[![NPM downloads][downloads-image]][downloads-url] |
| 5 | +[![Build status][travis-image]][travis-url] |
| 6 | +[![Test coverage][coveralls-image]][coveralls-url] |
| 7 | +[![Bundle size][bundlephobia-image]][bundlephobia-url] |
| 8 | + |
| 9 | +> Small JWT library using the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API). |
| 10 | +
|
| 11 | +## Installation |
| 12 | + |
| 13 | +```sh |
| 14 | +npm install @borderless/web-jwt --save |
| 15 | +``` |
| 16 | + |
| 17 | +## Usage |
| 18 | + |
| 19 | +```js |
| 20 | +import { encodeJwt, decodeJwt, verifyJwt } from "@borderless/web-jwt"; |
| 21 | + |
| 22 | +// Create a web crypto key. |
| 23 | +const key = crypto.subtle.importKey( |
| 24 | + "jwk", |
| 25 | + { |
| 26 | + kty: "oct", |
| 27 | + k: "4Vulge0qgl6janNxYmrYk-sao2wR5tpyKkh_sTLY2CQ", |
| 28 | + alg: "HS256", |
| 29 | + }, |
| 30 | + { name: "HMAC", hash: "SHA-256" }, |
| 31 | + false, |
| 32 | + ["sign", "verify"] |
| 33 | +); |
| 34 | + |
| 35 | +// Create a JWT and sign using the key. |
| 36 | +await encodeJwt( |
| 37 | + { |
| 38 | + alg: "HS256", |
| 39 | + }, |
| 40 | + { |
| 41 | + test: true, |
| 42 | + }, |
| 43 | + key |
| 44 | +); //=> "eyJhbGciOiJIUzI1NiJ9.eyJ0ZXN0Ijp0cnVlfQ.pQM0RvgTKjtAC1XmMnCK4vhgGycbg0vVLn0rsiE8BGc" |
| 45 | + |
| 46 | +// Decode the JWT. |
| 47 | +const jwt = await decodeJwt( |
| 48 | + "eyJhbGciOiJIUzI1NiJ9.eyJ0ZXN0Ijp0cnVlfQ.pQM0RvgTKjtAC1XmMnCK4vhgGycbg0vVLn0rsiE8BGc" |
| 49 | +); //=> { header, payload, ... } |
| 50 | + |
| 51 | +// Verify the decoded JWT _before_ trusting! |
| 52 | +const valid = await verifyJwt(jwt); //=> true |
| 53 | +``` |
| 54 | + |
| 55 | +## TypeScript |
| 56 | + |
| 57 | +This project is written using [TypeScript](https://github.com/Microsoft/TypeScript) and publishes the definitions directly to NPM. |
| 58 | + |
| 59 | +## License |
| 60 | + |
| 61 | +MIT |
| 62 | + |
| 63 | +[npm-image]: https://img.shields.io/npm/v/@borderless/web-jwt.svg?style=flat |
| 64 | +[npm-url]: https://npmjs.org/package/@borderless/web-jwt |
| 65 | +[downloads-image]: https://img.shields.io/npm/dm/@borderless/web-jwt.svg?style=flat |
| 66 | +[downloads-url]: https://npmjs.org/package/@borderless/web-jwt |
| 67 | +[travis-image]: https://img.shields.io/travis/BorderlessLabs/web-jwt.svg?style=flat |
| 68 | +[travis-url]: https://travis-ci.org/BorderlessLabs/web-jwt |
| 69 | +[coveralls-image]: https://img.shields.io/coveralls/BorderlessLabs/web-jwt.svg?style=flat |
| 70 | +[coveralls-url]: https://coveralls.io/r/BorderlessLabs/web-jwt?branch=master |
| 71 | +[bundlephobia-image]: https://img.shields.io/bundlephobia/minzip/@borderless/web-jwt.svg |
| 72 | +[bundlephobia-url]: https://bundlephobia.com/result?p=@borderless/web-jwt |
0 commit comments