A handy-dandy GraphQL directive for setting authentication requirement on fields.
yarn add graphql-is-authenticated
You want to include @isAuthenticated
directive on fields you wish to be restricted.
type Query {
teapot: String! @isAuthenticated
}
This will return an AuthenticationError
for users who are attempting to access this field, but are not authenticated.
You have two ways to specify if a user is authenticated:
You would define it as follows for Apollo Server or similar:
import {
createIsAuthenticatedDirective,
createIsAuthenticatedTypeDef
} from 'graphql-is-authenticated';
new ApolloServer({
typeDefs: [createIsAuthenticatedTypeDef(), ...otherTypeDefs],
schemaDirectives: {
isAuthenticated: createIsAuthenticatedDirective()
},
context: (ctx) => {
const isAuthenticated = checkIsUserAuthenticated();
return { isAuthenticated };
}
...
});
You can also pass a function as an argument to createIsAuthenticatedDirective
which takes an argument of context, and returns a promise which resolves a boolean.
import {
createIsAuthenticatedDirective,
createIsAuthenticatedTypeDef
} from 'graphql-is-authenticated';
const checkIsUserAuthenticated = async (ctx) => {
const { req } = ctx;
const { authorization } = ctx.headers;
if (!authorization) {
return false;
}
const isAuthenticated = await verifyAuthorizationHeader(authorization);
return isAuthenticated;
};
new ApolloServer({
typeDefs: [createIsAuthenticatedTypeDef(), ...otherTypeDefs],
schemaDirectives: {
isAuthenticated: createIsAuthenticatedDirective(checkIsUserAuthenticated)
}
...
});
Many thanks to the people below for supporting this project! 🎉