Skip to content

Tomburgs/graphql-is-authenticated

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GraphQL isAuthenticated

License Version Size Downloads

A handy-dandy GraphQL directive for setting authentication requirement on fields.

Install

yarn add graphql-is-authenticated

Usage

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:

Option 1: Set isAuthenticated on context

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 };
    }
    ...
});

Option 2: Pass checkIsUserAuthenticated method

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)
    }
    ...
});

Supporters

Many thanks to the people below for supporting this project! 🎉

Stargazers repo roster for @Tomburgs/graphql-is-authenticated Forkers repo roster for @Tomburgs/graphql-is-authenticated