{"id":13796694,"url":"https://github.com/jwtk/njwt","last_synced_at":"2025-05-15T16:05:04.747Z","repository":{"id":26433211,"uuid":"29883801","full_name":"jwtk/njwt","owner":"jwtk","description":"Node.js JWT support","archived":false,"fork":false,"pushed_at":"2023-05-01T16:36:56.000Z","size":519,"stargazers_count":430,"open_issues_count":51,"forks_count":48,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-05-02T03:13:16.912Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"horizons-school-of-technology/electron-react-quick-start","license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jwtk.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-01-26T21:59:26.000Z","updated_at":"2024-06-11T19:37:16.153Z","dependencies_parsed_at":"2024-06-11T19:53:14.427Z","dependency_job_id":null,"html_url":"https://github.com/jwtk/njwt","commit_stats":{"total_commits":117,"total_committers":15,"mean_commits":7.8,"dds":0.4700854700854701,"last_synced_commit":"84fa6e64d3a5e042a1ef8e92ae9cfb5ce06b28e4"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jwtk%2Fnjwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jwtk%2Fnjwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jwtk%2Fnjwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jwtk%2Fnjwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jwtk","download_url":"https://codeload.github.com/jwtk/njwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247791846,"owners_count":20996842,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T23:01:13.926Z","updated_at":"2025-04-08T06:31:28.199Z","avatar_url":"https://github.com/jwtk.png","language":"JavaScript","funding_links":[],"categories":["Libraries"],"sub_categories":["Node.js"],"readme":"# nJwt - JWTs for Node.js\n\n\"Nin-Jot\" /ˈnɪn.dʒɑt/\n\n[![NPM Version](https://img.shields.io/npm/v/njwt.svg?style=flat)](https://npmjs.org/package/njwt)\n[![NPM Downloads](https://img.shields.io/npm/dm/njwt.svg?style=flat)](https://npmjs.org/package/njwt)\n[![Build Status](https://img.shields.io/travis/jwtk/njwt.svg?style=flat)](https://travis-ci.org/jwtk/njwt)\n[![Coverage Status](https://coveralls.io/repos/jwtk/njwt/badge.svg?branch=master)](https://coveralls.io/r/jwtk/njwt?branch=master)\n\nnJwt is the cleanest JSON Web Token (JWT) library for Node.js developers. nJwt\nremoves all the complexities around JWTs, and gives you a simple, intuitive API,\nthat allows you to securely make and use JWTs in your applications without\nneeding to read [rfc7519](http://www.rfc-editor.org/rfc/rfc7519.txt).\n\n### Creating Secure, Signed JWTs\n\nJWTs expect *\"claims\"*, they are a set of assertions about who the user is and what\nthey can do.  The most common use case for JWTs is to declare the \"scope\" of the\naccess token, which is a list of things that the holder of the token (the user)\nis allowed to do.\n\nJWTs should be signed, otherwise you can't verify that they were created by you.\nOur library expects that you give us a highly random signing key for\nsigning tokens.  We use the `HS256` algorithm by default, and the byte length of\nthe signing key should match that of the signing algorithm, to ensure cryptographic\nsecurity.\n\nWhile the library will accept strings for signing keys, we suggest you use a\nBuffer instead.  Using buffers makes it easy to do other operations, like\nconvert your signing key to Base64URL encoding, if you need to transmit your\nkey to other systems.\n\nWhile the claims are completely up to you, we do recommend setting the \"Subject\"\nand \"Audience\" fields.\n\nJWTs commonly contain the `iat`, `nbf` and `exp` claims, which declare the time the\ntoken was issued, activation date and when it expires.  Our library will create these for you (except nbf),\nwith a default expiration of 1 hour. `nbf` is optional.\n\nHere is a simple example that shows you how to create a secure byte string for\nyour signing key, and then use that key to sign a JWT with some claims that you\nprovide:\n\n````javascript\nvar nJwt = require('njwt');\nvar secureRandom = require('secure-random');\n\nvar signingKey = secureRandom(256, {type: 'Buffer'}); // Create a highly random byte array of 256 bytes\n\nvar claims = {\n  iss: \"http://myapp.com/\",  // The URL of your service\n  sub: \"users/user1234\",    // The UID of the user in your system\n  scope: \"self, admins\"\n}\n\nvar jwt = nJwt.create(claims,signingKey);\n\n````\n\nOnce you have created the JWT, you can look at its internal structure by\nlogging it to the console.  This is our internal representation of the token,\nthis is not what you'll send to your end user:\n\n````javascript\nconsole.log(jwt);\n````\n````json\n{\n  \"header\": {\n    \"typ\": \"JWT\",\n    \"alg\": \"HS256\"\n  },\n  \"body\": {\n    \"jti\": \"c84280e6-0021-4e69-ad76-7a3fdd3d4ede\",\n    \"iat\": 1434660338,\n    \"exp\": 1434663938,\n    \"nbf\": 1434663938,\n    \"iss\": \"http://myapp.com/\",\n    \"sub\": \"users/user1234\",\n    \"scope\": [\"self\",\"admins\"]\n  }\n}\n````\nOur library has added the `jti` field for you, this is a random ID that will be\nunique for every token.  You can use this if you want to create a database of\ntokens that have been issued to the user.\n\nWhen you are ready to give the token to your end user, you need to compact it.\nThis will turn it into a Base64 URL encoded string, making it safe to pass\naround in browsers without any unexpected formatting applied to it.\n\n````javascript\nvar token = jwt.compact();\nconsole.log(token);\n````\n````\neyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE0MzQ0Nzk4ODN9.HQyx15jWm1upqsrKSf89X_iP0sg7N46a9pqBVGPMYdiqZeuU_ZZOdU-zizHJoIHMIJxtEWzpSMaVubJW0AJsTqjqQf6GoJ4cmFAfmfUFXmMC4Xv5oc4UqvGizpoLjfZedd834PcwbS-WskZcL4pVNmBIGRtDXkoU1j2X1P5M_sNJ9lYZ5vITyqe4MYJovQzNdQziUNhcMI5wkXncV7XzGInBeQsPquASWVG4gb3Y--k1P3xWA4Df3rKeEQBbInDKXczvDpfIlTojx4Ch8OM8vXWWNxW-mIQrV31wRrS9XtNoig7irx8N0MzokiYKrQ8WP_ezPicHvVPIHhz-InOw\n````\n\nThis is the JWT that the client application will retain, and use for authentication.\n\nYour server application will also need to persist the signing key that was used\nto sign the token, and when the client tries to use this token for\nauthentication, you will need to use the same signing key for verification.\n\nThe Buffer needs to be converted to a string so that it can be persisted in a\ndatabase, and you can do so like this:\n\n```\nvar base64SigningKey = signingKey.toString('base64');\n```\n\nIf you are going to use multiple signing keys, it is common practice to create a\nrandom ID which identifies the key, and store that ID with the key in your\ndatabase.  When you create JWTs, set the `kid` field of the header to be this ID.\nThen when verifying JWTs, this `kid` field will tell you which signing key should\nbe used for verification.\n\n### Verifying Signed JWTs\n\nThe end user will use their JWT to authenticate themselves with your service.\nWhen they present the JWT, you want to check the token to ensure that it's valid.\nThis library does the following checks when you call the `verify` method:\n\n* It was created by you (by verifying the signature, using the secret signing key)\n* It hasn't been modified (e.g. some claims were maliciously added)\n* It hasn't expired\n* It is active\n\nTo verify a previously issued token, use the `verify` method.  You must give it\nthe same signing key that you are using to create tokens:\n````javascript\nnJwt.verify(token,signingKey,function(err,verifiedJwt){\n  if(err){\n    console.log(err); // Token has expired, has been tampered with, etc\n  }else{\n    console.log(verifiedJwt); // Will contain the header and body\n  }\n});\n````\n\nIf validation fails you can look at `err.message` to understand the problem.  If\nthe header and body of the JWT were parse-able (not not verifiable) they will\nbe provided as objects at `err.parsedHeader` and `err.parsedBody`.\n\nYou can also use verify synchronously, in which case the errors will be thrown:\n\n````javascript\ntry{\n  verifiedJwt = nJwt.verify(token,signingKey);\n}catch(e){\n  console.log(e);\n}\n````\n\n### Changing the algorithm\n\nIf you want to change the algorithm from the default `HS256`, you can do so\nby passing it as a third argument to the `create` or `verify` methods:\n\n````javascript\nvar jwt = nJwt.create(claims,signingKey,'HS512');\n````\n````javascript\nnJwt.verify(token,signingKey, 'HS512');\n````\n\nSee the table below for a list of supported algorithms.  If using RSA key pairs,\nthe public key will be the signing key parameter.\n\n### Customizing the token\n\nWhile we've chosen secure, sensible defaults for you, you may need to change it\nup.\n\n#### Claims\n\nIf you need to provide custom claims, simply supply them to the `create` method\nor add them manually to the claims body after the JWT is created.  These two\nexamples create the same claims body:\n\n```javascript\nvar claims = {\n  scope: 'admins'\n}\n\nvar jwt = nJwt.create(claims,secret);\n\njwt.body.scope = 'admins';\n\njwt.setClaim('otherClaim', 'value');\n\n````\n\n#### Headers\n\nYou can manually modify headers object, or use the `setHeader()` method:\n\n```javascript\nvar jwt = nJwt.create({}, keyMap.kid_a);\n\njwt.headers.myClaim = 'foo';\n\njwt.setHeader('kid', 'kid_a');\n```\n\n### Using a key resolver\nIf your application is using multiple signing keys, nJwt provides a handy little feature that allows you to resolve which signing key should be used to verify a token.\n\nTo do this, you first need to manually create a verifier instance, using `nJwt.createVerifier()`, and then provide your key resolution function to the `withKeyResolver()` method:\n\n```javascript\nvar keyMap = {\n  kid_a: '\u003csecure signing key\u003e',\n  kid_b: '\u003csecure signing key\u003e'\n};\n\nfunction myKeyResolver(kid, cb) {\n  var key = keyMap[kid];\n\n  if (key) {\n    return cb(null, key);\n  }\n\n  cb(new Error('Unknown kid'));\n}\n\nvar tokenA = nJwt.create({}, keyMap.kid_a).setHeader('kid', 'kid_a').compact();\n\nvar tokenB = nJwt.create({}, 'foo').setHeader('kid', 'bar').compact();\n\nvar verifier = nJwt.createVerifier().withKeyResolver(myKeyResolver);\n\n// synchronously\n\ntry {\n\n  // This will pass and print the result\n\n  var parsedJwt = verifier.verify(tokenA);\n  console.log(parsedJwt);\n\n} catch(e) {\n  console.log(e);\n}\n\n// asynchronously\n\nverifier.verify(tokenB, function(err, verifiedJwt) {\n  if (err) {\n    return console.log(err);  // This error with \"'Error while resolving signing key for kid \"bar\"'\"\n  }\n\n  console.log(verifiedJwt);\n});\n```\n\n\n\n#### Expiration Claim\n\nA convenience method is supplied for modifying the `exp` claim.  You can modify\nthe `exp` claim by passing a `Date` object, or a millisecond value, to the\n`setExpiration` method:\n\n```javascript\nvar jwt = nJwt.create(claims,secret);\n\njwt.setExpiration(new Date('2015-07-01')); // A specific date\njwt.setExpiration(new Date().getTime() + (60*60*1000)); // One hour from now\njwt.setExpiration(); // Remove the exp claim\n```\n\n#### NotBefore Claim\n\nA convenience method is supplied for modifying the `nbf` claim.  You can modify\nthe `nbf` claim by passing a `Date` object, or a millisecond value, to the\n`setNotBefore` method:\n\n```javascript\nvar jwt = nJwt.create(claims,secret);\n\njwt.setNotBefore(new Date('2015-07-01')); // token is active from this date\njwt.setNotBefore(new Date().getTime() + (60*60*1000)); // One hour from now\njwt.setNotBefore(); // Remove the exp claim\n```\n\n\n## Supported Algorithms\n\n\"alg\" Value | Algorithm used\n------------|----------------------------\nHS256 | HMAC using SHA-256 hash algorithm\nHS384 | HMAC using SHA-384 hash algorithm\nHS512 | HMAC using SHA-512 hash algorithm\nRS256 | RSASSA using SHA-256 hash algorithm\nRS384 | RSASSA using SHA-384 hash algorithm\nRS512 | RSASSA using SHA-512 hash algorithm\nES256 | ECDSA using P-256 curve and SHA-256 hash algorithm\nES384 | ECDSA using P-384 curve and SHA-384 hash algorithm\nES512 | ECDSA using P-521 curve and SHA-512 hash algorithm\nnone | No digital signature or MAC value included\n\n## Unsupported features\n\nThe following features are not yet supported by this library:\n\n* Encrypting the JWT (aka JWE)\n\n## TypeScript usage\n\nThis package includes TypeScript definitions for library interface. They can be used as follows:\n\n```typescript\nimport { Jwt, create } from 'njwt';\nimport crypto = require('crypto');\n\nconst signingKey: Buffer = crypto.randomBytes(256); // Create a highly random byte array of 256 bytes\nconst claims = {\n  iss: 'http://myapp.com/',  // The URL of your service\n};\nconst jwt: Jwt = create(claims, signingKey);\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjwtk%2Fnjwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjwtk%2Fnjwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjwtk%2Fnjwt/lists"}