{"id":14976200,"url":"https://github.com/graphql-community/graphql-directive-auth","last_synced_at":"2025-07-21T17:31:52.712Z","repository":{"id":32787652,"uuid":"142468786","full_name":"graphql-community/graphql-directive-auth","owner":"graphql-community","description":"GraphQL directive for handling auth","archived":false,"fork":false,"pushed_at":"2023-01-06T01:41:55.000Z","size":3335,"stargazers_count":136,"open_issues_count":23,"forks_count":12,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-06-27T05:45:03.084Z","etag":null,"topics":["auth","authentication","authorization","graphql","graphql-directive","graphql-server"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/graphql-community.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}},"created_at":"2018-07-26T16:49:18.000Z","updated_at":"2024-07-30T06:31:21.000Z","dependencies_parsed_at":"2023-01-14T22:13:55.070Z","dependency_job_id":null,"html_url":"https://github.com/graphql-community/graphql-directive-auth","commit_stats":null,"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"purl":"pkg:github/graphql-community/graphql-directive-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-community%2Fgraphql-directive-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-community%2Fgraphql-directive-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-community%2Fgraphql-directive-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-community%2Fgraphql-directive-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/graphql-community","download_url":"https://codeload.github.com/graphql-community/graphql-directive-auth/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-community%2Fgraphql-directive-auth/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266342809,"owners_count":23914262,"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","status":"online","status_checked_at":"2025-07-21T11:47:31.412Z","response_time":64,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["auth","authentication","authorization","graphql","graphql-directive","graphql-server"],"created_at":"2024-09-24T13:53:29.646Z","updated_at":"2025-07-21T17:31:52.691Z","avatar_url":"https://github.com/graphql-community.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# graphql-directive-auth\n\n[![Version][version-badge]][package]\n[![downloads][downloads-badge]][npmtrends]\n[![PRs Welcome][prs-badge]][prs]\n[![MIT License][license-badge]][build]\n\n# Introduction\n\nThe `graphql-directive-auth` was created to help with common authentication tasks that is faced in almost every API.\n\n# Table of Contents\n\n- [graphql-directive-auth](#graphql-directive-auth)\n- [Introduction](#introduction)\n- [Table of Contents](#table-of-contents)\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Default](#default)\n    - [What `default` means, and what I **need to do**?](#what-default-means-and-what-i-need-to-do)\n    - [Example:](#example)\n  - [Custom behaviour of authentication functions](#custom-behaviour-of-authentication-functions)\n  - [Custom check role function](#custom-check-role-function)\n    - [How to create your own function](#how-to-create-your-own-function)\n- [Directive Parameters](#directive-parameters)\n  - [Contributing](#contributing)\n- [LICENSE](#license)\n\n# Installation\n\n```\nyarn add graphql-directive-auth\n```\n\n# Usage\n\nWe are able to use directives in two different way:\n\n## Default\n\nTo use the default directive behaviour, you need to set `APP_SECRET` environment variable, and that's all.\n\n### What `default` means, and what do I **need to do**?\n\n- `@isAuthenticated` - Just after you set environment variables, you need to have a valid JWT token and send it by `Authorization` in the HTTP headers. That's all, the directive will check your token and throw an error if the token is invalid or expired.\n- `@hasRole` - Checks roles of an authenticated user. To use it correctly, inside your JWT token you should have the `role` property with the correct role. If the user role doesn't match with the provided role, then directive will throw an error.\n\n\u003e `@hasRole` before checking role is doing authentication to get roles from JWT token.\n\n### Example:\n\n```js\nimport { AuthDirective } from 'graphql-directive-auth';\n// or\nconst AuthDirective = require('graphql-directive-auth').AuthDirective;\n\n// set environment variable, but in better way ;)\nprocess.env.APP_SECRET = 'your_secret_key';\n\nconst schema = makeExecutableSchema({\n  typeDefs,\n  resolvers,\n  schemaDirectives: {\n    // to use @hasRole and @isAuthenticated directives\n    ...AuthDirective(),\n    // custom name for @isAuthenticated\n    auth: AuthDirective().isAuthenticated,\n    // custom name for @hasRole\n    role: AuthDirective().hasRole,\n  },\n});\n```\n\n## Custom behaviour of authentication functions\n\nIf you need custom Authentication you can pass your authentication function to the main `AuthDirective` functions. Your authentication function should return an object which will be available via `context.auth`.\n\nAuthentication function signature:\n\n```js\ncontext =\u003e {\n  // your logic here\n\n  // you should return an object\n  // this object will be passed inside your resolver\n  // it is available inside context via auth property\n  return {\n    user: {\n      id: 'your_user_id',\n    },\n  };\n};\n```\n\nusage:\n\n```js\nimport { AuthDirective } from 'graphql-directive-auth';\n// or\nconst AuthDirectives = require('graphql-directive-auth').AuthDirective;\n\nconst customAuth = AuthDirectives({\n  authenticateFunc: authenticateCustomFunc,\n  checkRoleFunc: checkRoleCustomFunc\n});\n\nconst schema = makeExecutableSchema({\n  typeDefs,\n  resolvers,\n  schemaDirectives: {\n    // to use @hasRole and @isAuthenticated directives\n    ...customAuth,\n    // custom name for @isAuthenticated\n    auth: customAuth().isAuthenticated,\n    // custom name for @hasRole\n    role: customAuth().hasRole,\n  },\n```\n\nresolver:\n\n```js\nexport default {\n  Query: {\n    me() (root, args, ctx){\n      const userId = ctx.auth.user.id; // your_user_id\n    },\n  },\n};\n```\n\n## Custom check role function\n\nSame as with the authenticate function, you can add your own logic to checking roles. Here is an example of implementation:\n\n```js\nimport { AuthenticationError } from 'apollo-server';\nimport jwt from 'jsonwebtoken';\nimport { jwtSecret } from '../config';\n\nexport default (ctx, value) =\u003e {\n  const authorization =\n    ctx.request \u0026\u0026 ctx.request.headers \u0026\u0026 ctx.request.headers.authorization;\n\n  if (!authorization) {\n    throw new AuthenticationError('Unauthorized access!');\n  }\n\n  const token = authorization.replace('Bearer ', '');\n\n  const decodedToken = jwt.verify(token, jwtSecret);\n\n  const mandatoryRoles = value.split(',').map((s) =\u003e s.trim());\n\n  if (decodedToken \u0026\u0026 decodedToken.user \u0026\u0026 decodedToken.user.roles) {\n    const { roles } = decodedToken.user;\n    const rolesIntersection = roles.filter((role) =\u003e\n      mandatoryRoles.includes(role),\n    );\n\n    if (rolesIntersection.length === 0) {\n      throw new AuthenticationError('Invalid role!');\n    }\n\n    return rolesIntersection;\n  }\n\n  throw new AuthenticationError('Invalid token!');\n};\n```\n\n### How to create your own function\n\n- Function accepts two parameters, one is the context and the second is the value from the directive\n- To reject an access to the particular field, you need to throw an Error that will be caught by the directive and returned if required.\n- Function doesn't need to return anything special\n\n# Directive Parameters\n\n- '@isAuthenticated' - checks if user is authenticated\n- '@hasRole(role: \"user, admin\")' - checks if user is authenticated and has the specified roles\n\n\u003e if you use [`graphql-import`](https://github.com/prismagraphql/graphql-import) then you need to add this definition on top of the schema:\n\n```graphql\ndirective @isAuthenticated on FIELD | FIELD_DEFINITION\ndirective @hasRole(role: String) on FIELD | FIELD_DEFINITION\n```\n\n## Contributing\n\nI would love to see your contribution. ❤️\n\nFor local development (and testing), all you have to do is to run `yarn` and then `yarn dev`. This will start the Apollo server and you are ready to contribute :tada:\n\nRun yarn test (try `--watch` flag) for unit tests (we are using Jest)\n\n# LICENSE\n\nThe MIT License (MIT) 2018 - Luke Czyszczonik - \u003cmailto:lukasz.czyszczonik@gmail.com\u003e\n\n[npm]: https://www.npmjs.com/\n[node]: https://nodejs.org\n[build-badge]: https://img.shields.io/travis/graphql-community/graphql-directive-auth.svg?style=flat-square\n[build]: https://travis-ci.org/graphql-community/graphql-directive-auth\n[coverage-badge]: https://img.shields.io/codecov/c/github/graphql-community/graphql-directive-auth.svg?style=flat-square\n[coverage]: https://codecov.io/github/graphql-community/graphql-directive-auth\n[version-badge]: https://img.shields.io/npm/v/graphql-directive-auth.svg?style=flat-square\n[package]: https://www.npmjs.com/package/graphql-directive-auth\n[downloads-badge]: https://img.shields.io/npm/dm/graphql-directive-auth.svg?style=flat-square\n[npmtrends]: http://www.npmtrends.com/graphql-directive-auth\n[license-badge]: https://img.shields.io/npm/l/graphql-directive-auth.svg?style=flat-square\n[license]: https://github.com/graphql-community/graphql-directive-auth/blob/master/LICENSE\n[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square\n[prs]: http://makeapullrequest.com\n[donate-badge]: https://img.shields.io/badge/$-support-green.svg?style=flat-square\n[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square\n[coc]: https://github.com/graphql-community/graphql-directive-auth/blob/master/CODE_OF_CONDUCT.md\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-community%2Fgraphql-directive-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgraphql-community%2Fgraphql-directive-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-community%2Fgraphql-directive-auth/lists"}