graphql-anonymous-extension
An apollo-server extension for managing a secure graphql
Install
npm install graphql-anonymous-extension
Usage
By default all queries and mutation are authenticated/authorize by calling the authFunc
, only when marked with @anonymous
directive the authFunc
will not called and let the resolver do it's job.
authFunc
will be called if one or more queries or mutations DO NOT have @anonymous
directive mark on them
NOTES:
isAuth
function called beforeauthFunc
will called to avoid re-authenticate/authorize in the same request for different fieldsauthFunc
works only with synchronious function
Example
const ApolloServer gql AuthenticationError ForbiddenError = ;const AnonymousExtension AnonymousDirective = ; const typeDefs = gql` # or directive @anonymous on FIELD_DEFINITION type Query { public: String! @ private: String! private2: String! } type Mutation { changeSecret(secret: String!): String! changeNothing: String! @anonymous }`; const resolvers = Query: 'public!' 'private!' 'private2!' Mutation: `success change secret to ` 'did nothing important' ; const authenticate = { if !ctxtoken throw 'no token'; if ctxtoken !== 'p@ssword' throw 'invalid'; ctxuser = true;}; const isAuthenticated = ctxuser; const server = typeDefs resolvers token: req extensions: authenticate isAuthenticated; server ;