graphql-directive-auth is a utility library designed to simplify common authentication and authorization tasks in GraphQL APIs by providing schema directives. It offers `@isAuthenticated` and `@hasRole` directives, which can be used to protect fields and types based on JWT tokens and user roles. The current stable version is 0.3.2, indicating it's still in a pre-1.0 development phase, which typically implies an irregular release cadence and potential for API changes. Its key differentiators include a straightforward setup with environment variables for default behavior and highly customizable authentication and role-checking functions for more complex scenarios. It ships with TypeScript types, enhancing developer experience in TypeScript projects. It integrates with `graphql-tools` and expects a `graphql` peer dependency, providing a declarative approach to security within the GraphQL schema itself.
npm install graphql-directive-authVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up `graphql-directive-auth` with default authentication, protecting types and fields using `@isAuthenticated` and `@hasRole` directives, and accessing authenticated user data within resolvers. It includes type definitions, resolvers, and directive registration.
Refer to the package's changelog or GitHub releases for specific upgrade instructions when updating across minor or major pre-1.0 versions. Thorough testing is recommended.
Ensure `process.env.APP_SECRET` is set to a strong, consistent secret key. For `@hasRole`, verify that the JWT token, when decoded, includes a `role` property matching the expected string. If custom logic is needed, implement `authenticateFunc` and `checkRoleFunc`.
Standardize the return structure of your custom `authenticateFunc`. Always check for the existence of `ctx.auth` and its properties within resolvers before accessing them, especially if authentication is optional or conditional for certain fields.
Ensure a valid, unexpired JWT token is sent in the `Authorization` header. Verify `APP_SECRET` is correctly set and matches the key used to sign the token.
Check the `role` value in the JWT token (e.g., using jwt.io). Ensure it exactly matches the `role` argument provided to the `@hasRole` directive in your schema. If using a custom `checkRoleFunc`, debug its logic.
Add null/undefined checks before accessing properties of `ctx.auth` within resolvers (e.g., `if (ctx.auth?.user?.id) { ... }`). Review your custom `authenticateFunc` to ensure it always returns an object with the expected `user` property if authentication is successful.