{"id":13836097,"url":"https://github.com/fastify/fastify-bearer-auth","last_synced_at":"2025-05-15T10:01:07.802Z","repository":{"id":19842360,"uuid":"88060345","full_name":"fastify/fastify-bearer-auth","owner":"fastify","description":"A Fastify plugin to require bearer Authorization headers","archived":false,"fork":false,"pushed_at":"2025-05-01T06:03:07.000Z","size":214,"stargazers_count":173,"open_issues_count":0,"forks_count":29,"subscribers_count":15,"default_branch":"main","last_synced_at":"2025-05-01T07:19:23.372Z","etag":null,"topics":["fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/bearer-auth","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"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,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2017-04-12T14:20:04.000Z","updated_at":"2025-05-01T06:03:04.000Z","dependencies_parsed_at":"2023-01-13T20:37:35.687Z","dependency_job_id":"24d3609b-d6a0-4bbc-94ac-dc5e050fd6cb","html_url":"https://github.com/fastify/fastify-bearer-auth","commit_stats":{"total_commits":191,"total_committers":35,"mean_commits":5.457142857142857,"dds":0.7015706806282722,"last_synced_commit":"1c125d76ffccb1645ea0a7cfa67e4ba9b7a03303"},"previous_names":[],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-bearer-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-bearer-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-bearer-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-bearer-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-bearer-auth/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254319715,"owners_count":22051072,"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":["fastify","fastify-plugin"],"created_at":"2024-08-04T15:00:35.519Z","updated_at":"2025-05-15T10:01:07.371Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/bearer-auth\n\n[![CI](https://github.com/fastify/fastify-bearer-auth/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-bearer-auth/actions/workflows/ci.yml)\n[![npm version](https://img.shields.io/npm/v/@fastify/bearer-auth)](https://www.npmjs.com/package/@fastify/bearer-auth)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\n*@fastify/bearer-auth* provides a simple Bearer auth request hook for the [Fastify][fastify]\nweb framework.\n\n[fastify]: https://fastify.dev/\n\n\n## Install\n```\nnpm i @fastify/bearer-auth\n```\n\n### Compatibility\n| Plugin version | Fastify version |\n| ---------------|-----------------|\n| `^10.x`        | `^5.x`          |\n| `^8.x`         | `^4.x`          |\n| `^5.x`         | `^3.x`          |\n| `^4.x`         | `^2.x`          |\n| `^1.x`         | `^1.x`          |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n## Example\n\n```js\n'use strict'\n\nconst fastify = require('fastify')()\nconst bearerAuthPlugin = require('@fastify/bearer-auth')\nconst keys = new Set(['a-super-secret-key', 'another-super-secret-key'])\n\nfastify.register(bearerAuthPlugin, {keys})\nfastify.get('/foo', (req, reply) =\u003e {\n  reply.send({authenticated: true})\n})\n\nfastify.listen({port: 8000}, (err) =\u003e {\n  if (err) {\n    fastify.log.error(err.message)\n    process.exit(1)\n  }\n  fastify.log.info('http://127.0.0.1:8000/foo')\n})\n```\n\n## API\n\n*@fastify/bearer-auth* exports a standard [Fastify plugin](https://github.com/fastify/fastify-plugin).\nThis allows registering the plugin within scoped paths, so some paths can be protected\nby the plugin while others are not. See the [Fastify](https://fastify.dev/docs/latest)\ndocumentation and examples for more details.\n\nWhen registering the plugin a configuration object must be specified:\n\n* `keys`: A `Set` or array with valid keys of type `string` (required)\n* `function errorResponse (err) {}`: Method must synchronously return the content body to be\nsent to the client (optional)\n* `contentType`: If the content to be sent is anything other than\n`application/json`, then the `contentType` property must be set (optional)\n* `bearerType`: String specifying the Bearer string (optional)\n* `specCompliance`:\nPlugin spec compliance. Accepts either\n[`rfc6749`](https://datatracker.ietf.org/doc/html/rfc6749) or\n[`rfc6750`](https://datatracker.ietf.org/doc/html/rfc6750).\nDefaults to `rfc6750`.\n  * `rfc6749` is about the generic OAuth2.0 protocol, which allows the token type to be case-insensitive\n  * `rfc6750` is about the Bearer Token Usage, which forces the token type to be an exact match\n* `function auth (key, req) {}` : This function tests if `key` is a valid token. It must return\n  `true` if accepted or `false` if rejected. The function may also return a promise that resolves\n  to one of these values. If the function returns or resolves to any other value, rejects, or throws,\n  an HTTP status of `500` will be sent. `req` is the Fastify request object. If `auth` is a function,\n  `keys` will be ignored. If `auth` is not a function or `undefined`, `keys` will be used\n* `addHook`: Accepts a boolean, `'onRequest'`, or `'preParsing'` (optional, defaults to `'onRequest'`):\n  * `true` registers an `onRequest` hook\n  * `'onRequest'` and `'preParsing'` registers their respective hooks\n  * `false` will not register a hook, and the `fastify.verifyBearerAuth` and `fastify.verifyBearerAuthFactory` decorators will be exposed\n* `verifyErrorLogLevel`: An optional string specifying the log level for verification errors.\n  It must be a valid log level supported by Fastify, or an exception will be thrown when\n  registering the plugin. By default, this option is set to `error`\n\nThe default configuration object is:\n\n  ```js\n  {\n    keys: new Set(),\n    contentType: undefined,\n    bearerType: 'Bearer',\n    specCompliance: 'rfc6750',\n    errorResponse: (err) =\u003e {\n      return {error: err.message}\n    },\n    auth: undefined,\n    addHook: true\n}\n```\n\nThe plugin registers a standard Fastify [onRequest hook][onrequesthook] to inspect the request's\nheaders for an `authorization` header in the format `bearer key`. The `key` is matched against\nthe configured `keys` object using a [constant time algorithm](https://en.wikipedia.org/wiki/Time_complexity#Constant_time)\nto prevent [timing-attacks](https://snyk.io/blog/node-js-timing-attack-ccc-ctf/). If the\n`authorization` header is missing, malformed, or the `key` does not validate, a 401 response\nis sent with a `{error: message}` body, and no further request processing is performed.\n\n[onrequesthook]: https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md#onrequest\n\n## Integration with `@fastify/auth`\n\nThis plugin can integrate with `@fastify/auth` by following this example:\n\n```js\nconst fastify = require('fastify')()\nconst auth = require('@fastify/auth')\nconst bearerAuthPlugin = require('@fastify/bearer-auth')\nconst keys = new Set(['a-super-secret-key', 'another-super-secret-key'])\n\nasync function server() {\n\n  await fastify\n    .register(auth)\n    .register(bearerAuthPlugin, { addHook: false, keys, verifyErrorLogLevel: 'debug' })\n    .decorate('allowAnonymous', function (req, reply, done) {\n      if (req.headers.authorization) {\n        return done(Error('not anonymous'))\n      }\n      return done()\n    })\n\n  fastify.route({\n    method: 'GET',\n    url: '/multiauth',\n    preHandler: fastify.auth([\n      fastify.allowAnonymous,\n      fastify.verifyBearerAuth\n    ]),\n    handler: function (_, reply) {\n      reply.send({ hello: 'world' })\n    }\n  })\n\n  await fastify.listen({port: 8000})\n}\n\nserver()\n```\n\nPassing `{ addHook: false }` in the options causes the `verifyBearerAuth` hook to invoke\n`done(someError)` instead of immediately replying on error (`reply.send(someError)`). This allows\n`fastify.auth` to continue with the next authentication scheme in the hook list.\nSetting `{ verifyErrorLogLevel: 'debug' }` in the options makes `@fastify/bearer-auth` emit\nall verification error logs at the `debug` level. If `verifyBearerAuth` is the last hook in the list,\n`fastify.auth` will reply with `Unauthorized`.\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["\u003ch2 align=\"center\"\u003eAwesome Fastify\u003c/h2\u003e","JavaScript"],"sub_categories":["\u003ch2 align=\"center\"\u003eEcosystem\u003c/h2\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-bearer-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-bearer-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-bearer-auth/lists"}