We are able to use directives in two different way:
Default
To use the default directive behaviour, you need to set APP_SECRET environment variable, and that's all.
What default means, and what do I need to do?
@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.
@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.
@hasRole before checking role is doing authentication to get roles from JWT token.
Example:
import{AuthDirective}from'graphql-directive-auth';// orconstAuthDirective=require('graphql-directive-auth').AuthDirective;// set environment variable, but in better way ;)process.env.APP_SECRET='your_secret_key';constschema=makeExecutableSchema({
typeDefs,
resolvers,schemaDirectives: {// to use @hasRole and @isAuthenticated directives
...AuthDirective(),// custom name for @isAuthenticatedauth: AuthDirective().isAuthenticated,// custom name for @hasRolerole: AuthDirective().hasRole,},});
Custom behaviour of authentication functions
If 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.
Authentication function signature:
context=>{// your logic here// you should return an object// this object will be passed inside your resolver// it is available inside context via auth propertyreturn{user: {id: 'your_user_id',},};};
usage:
import{AuthDirective}from'graphql-directive-auth';// orconstAuthDirectives=require('graphql-directive-auth').AuthDirective;constcustomAuth=AuthDirectives({authenticateFunc: authenticateCustomFunc,checkRoleFunc: checkRoleCustomFunc});constschema=makeExecutableSchema({typeDefs,
resolvers,schemaDirectives: {// to use @hasRole and @isAuthenticated directives
...customAuth,// custom name for @isAuthenticatedauth: customAuth().isAuthenticated,// custom name for @hasRolerole: customAuth().hasRole,},
For 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
请发表评论