{"id":18256907,"url":"https://github.com/mediacomem/express-jwt-policies","last_synced_at":"2026-04-26T22:31:49.537Z","repository":{"id":73832485,"uuid":"111382392","full_name":"MediaComem/express-jwt-policies","owner":"MediaComem","description":"Lightweight JWT authentication \u0026 authorization middleware for Express","archived":false,"fork":false,"pushed_at":"2017-11-28T12:15:13.000Z","size":111,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-02-14T17:43:25.850Z","etag":null,"topics":["authentication","authorization","express","jwt","policy"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MediaComem.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","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":"2017-11-20T08:28:38.000Z","updated_at":"2017-11-21T10:20:16.000Z","dependencies_parsed_at":"2023-05-02T21:55:21.086Z","dependency_job_id":null,"html_url":"https://github.com/MediaComem/express-jwt-policies","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MediaComem%2Fexpress-jwt-policies","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MediaComem%2Fexpress-jwt-policies/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MediaComem%2Fexpress-jwt-policies/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MediaComem%2Fexpress-jwt-policies/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MediaComem","download_url":"https://codeload.github.com/MediaComem/express-jwt-policies/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247938578,"owners_count":21021553,"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":["authentication","authorization","express","jwt","policy"],"created_at":"2024-11-05T10:24:05.705Z","updated_at":"2026-04-26T22:31:49.530Z","avatar_url":"https://github.com/MediaComem.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# express-jwt-policies\n\nLightweight [JWT][jwt] authentication \u0026 authorization middleware for [Express][express].\n\n[![npm version](https://badge.fury.io/js/express-jwt-policies.svg)](https://badge.fury.io/js/express-jwt-policies)\n[![Dependency Status](https://gemnasium.com/badges/github.com/MediaComem/express-jwt-policies.svg)](https://gemnasium.com/github.com/MediaComem/express-jwt-policies)\n[![Build Status](https://travis-ci.org/MediaComem/express-jwt-policies.svg?branch=master)](https://travis-ci.org/MediaComem/express-jwt-policies)\n[![Coverage Status](https://coveralls.io/repos/github/MediaComem/express-jwt-policies/badge.svg?branch=master)](https://coveralls.io/github/MediaComem/express-jwt-policies?branch=master)\n[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.txt)\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n\n- [Usage](#usage)\n  - [Authentication only](#authentication-only)\n  - [Authorization only](#authorization-only)\n  - [Asynchronous authorization](#asynchronous-authorization)\n- [Configuration](#configuration)\n  - [Module options](#module-options)\n  - [Authentication options](#authentication-options)\n  - [Authorization options](#authorization-options)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\nDeveloped at the [Media Engineering Institute](http://mei.heig-vd.ch) ([HEIG-VD](https://heig-vd.ch)).\n\n\n\n## Usage\n\n**jwt-express-policies** is an opinionated JWT-based authentication \u0026\nauthorization middleware.  It assumes that:\n\n* Authentication is performed by sending a JWT bearer token in the\n  Authorization header.\n* Some JWTs may optionally correspond to a resource (e.g. a user in the\n  database) that you will need to load.\n\nThis module does **not** handle authentication or authorization errors for you.\nIt simply passes them down the middleware chain, leaving you the responsibility\nof responding adequately to the user:\n\n* Authentication errors will have the `status` property set to [401][http-401].\n  Properties may also be added by [express-jwt][express-jwt] which is used to\n  check the JWT.\n* Authorization errors will have the `status` property set to [403][http-403].\n\n```js\nconst express = require('express');\nconst jwtExpressPolicies = require('jwt-express-policies');\n\n// Configure the module.\nconst authorize = jwtExpressPolicies({\n\n  // Provide a function to load the authenticated resource.\n  authenticatedResourceLoader: function(req, res, next) {\n    new User().where({ id: req.jwtToken.sub }).then(user =\u003e {\n      req.currentUser = user;\n      next();\n    }).catch(next);\n  },\n\n  // Provide the secret used to sign JWTs.\n  jwtSecret: 'changeme'\n});\n\n// Create policies.\nconst stuffPolicy = {\n\n  // Any authenticated user can retrieve stuff.\n  canRetrieve: function(req) {\n    return req.currentUser;\n  },\n\n  // Only admins can create stuff.\n  canCreate: function(req) {\n    return req.currentUser \u0026\u0026 req.currentUser.hasRole('admin');\n  }\n};\n\n// Create your routes and plug in authorization as middleware.\nconst router = express.Router();\n\nrouter.get('/protected/stuff',\n  authorize(stuffPolicy.canRetrieve),\n  function(req, res, next) { /* retrieve implementation */ });\n\nrouter.post('/protected/stuff',\n  authorize(stuffPolicy.canCreate),\n  function(req, res, next) { /* create implementation */ });\n\n// Handle authentication/authorization errors.\nrouter.use((err, req, res, next) =\u003e {\n  res.status(err.status || 500).send(err.message);\n});\n```\n\n### Authentication only\n\n```js\n// Configure the module.\nconst auth = jwtExpressPolicies({\n  // ...\n});\n\nrouter.get('/protected/stuff',\n  auth.authenticate(),\n  function(req, res, next) { /* retrieve implementation */ });\n```\n\n### Authorization only\n\n```js\n// Configure the module.\nconst auth = jwtExpressPolicies({\n  // ...\n});\n\n// Use the `authenticate` option of the `authorize` function to\nrouter.get('/protected/stuff',\n  auth.authorize(policy.canRetrieve, { authenticate: false }),\n  function(req, res, next) { /* retrieve implementation */ });\n```\n\n### Asynchronous authorization\n\nPolicy functions may return a promise to perform asynchronous checks:\n\n```js\nconst stuffPolicy = {\n  canCreate: async function(req) {\n    if (!req.currentUser) {\n      return false;\n    } else {\n      const permissions = await fetchUserPermissions(req.currentUser);\n      return permissions.indexOf('stuff:create') \u003e= 0;\n    }\n  }\n};\n```\n\n\n\n## Configuration\n\n### Module options\n\nThese options can be passed to the function returned by\n`require('jwt-express-policies')` to configure the module:\n\n* `jwtSecret` (string) **required** - The secret used to sign JWTs.\n\n* `jwtRequestProperty` (string) - The property of the request to which the JWT\n  should be attached (`jwtToken` by default).\n\n  ```js\n  const auth = jwtExpressPolicies({\n    jwtSecret: 'changeme',\n    jwtRequestProperty: 'token',\n    // ...\n  });\n  ```\n\n* `authenticatedResourceLoader` (function) **required** - An Express middleware\n  function that will be called when a valid JWT bearer token is sent in the\n  Authorization header. The JWT will be available as the `req.jwtToken`\n  property (by default). It should load whatever resource is identified by the\n  token (e.g. a user) and attach it to the request (e.g. to the\n  `req.currentUser` property) if necessary. You may do nothing but call\n  `next()` in this function if the JWT is sufficient and nothing needs to be\n  loaded.\n\n  ```js\n  const auth = jwtExpressPolicies({\n    authenticatedResourceLoader: function(req, res, next) {\n      new User().where({ id: req.jwtToken.sub }).then(user =\u003e {\n        req.currentUser = user;\n        next();\n      }).catch(next);\n    },\n    // ...\n  });\n  ```\n\n* `authenticationRequired` (boolean) - If true, successful authentication is\n  always required. Otherwise, an unauthenticated request will not cause an\n  error. It is true by default. It can be set here at the module level, or\n  overridden at every authentication or authorization call.\n\n### Authentication options\n\nThese options can be passed when calling the module's `authenticate` function:\n\n* `authenticationRequired` (boolean) - Whether successful authentication is\n  required. If true, an error will be passed through the middleware chain if no\n  valid JWT is found in the Authorization header. If false, an unauthenticated\n  request will not cause an error, and the authenticated resource loader will\n  not be called. This defaults to the value of the `authenticationRequired`\n  option provided when configuring the module (true by default).\n\nThe entire options object (including any custom option you might add) is\nattached to the request as `req.authOptions`.\n\n### Authorization options\n\nThese options can be passed when calling the `authorize` function (which is\nalso the function returned by configuring the module):\n\n* `authenticate` (boolean) - Whether to perform authentication before\n  authorization. Defaults to true.\n* `authenticationRequired` (boolean) - Whether successful authentication is\n  required before performing authorization with the policy function. This\n  defaults to the value of the `authenticationRequired` option provided when\n  configuring the module (true by default).\n\nThe entire options object (including any custom option you might add) is\nattached to the request as `req.authOptions`.\n\n\n\n[express]: https://expressjs.com\n[express-jwt]: https://github.com/auth0/express-jwt\n[http-401]: https://httpstatuses.com/401\n[http-403]: https://httpstatuses.com/403\n[jwt]: https://jwt.io\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmediacomem%2Fexpress-jwt-policies","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmediacomem%2Fexpress-jwt-policies","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmediacomem%2Fexpress-jwt-policies/lists"}