All Projects → graphql-community → Graphql Directive Auth

graphql-community / Graphql Directive Auth

Licence: mit
GraphQL directive for handling auth

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Graphql Directive Auth

Annon.api
Configurable API gateway that acts as a reverse proxy with a plugin system.
Stars: ✭ 306 (+155%)
Mutual labels:  authentication, authorization, auth
Aws Serverless Auth Reference App
Serverless reference app and backend API, showcasing authentication and authorization patterns using Amazon Cognito, Amazon API Gateway, AWS Lambda, and AWS IAM.
Stars: ✭ 724 (+503.33%)
Mutual labels:  authentication, authorization, auth
Awesome Auth
📊 Software and Libraries for Authentication & Authorization
Stars: ✭ 520 (+333.33%)
Mutual labels:  authentication, authorization, auth
Huge
Simple user-authentication solution, embedded into a small framework.
Stars: ✭ 2,125 (+1670.83%)
Mutual labels:  authentication, authorization, auth
Next Authentication
Authentication & Authorization library for the Next.js framework
Stars: ✭ 55 (-54.17%)
Mutual labels:  authentication, authorization, auth
Mosquitto Go Auth
Auth plugin for mosquitto.
Stars: ✭ 212 (+76.67%)
Mutual labels:  authentication, authorization, auth
Php Auth
Authentication for PHP. Simple, lightweight and secure.
Stars: ✭ 713 (+494.17%)
Mutual labels:  authentication, authorization, auth
Social Core
Python Social Auth - Core
Stars: ✭ 618 (+415%)
Mutual labels:  authentication, authorization, auth
Laravel5.7 Vue Cli3 Boilerplate
Boilerplate / Starter kit. Laravel 5.7, Vue CLI 3 — Authentication with Email Verification. REST API.
Stars: ✭ 52 (-56.67%)
Mutual labels:  authentication, authorization, auth
Got Auth Service
A professional role-based-authorization(also supports resource and group) service with restful and graphql api for enterprise applications.
Stars: ✭ 12 (-90%)
Mutual labels:  graphql, authorization, auth
Vuejs2 Authentication Tutorial
Stars: ✭ 144 (+20%)
Mutual labels:  authentication, authorization, auth
Brandenburg
Laravel Authentication Package
Stars: ✭ 79 (-34.17%)
Mutual labels:  authentication, authorization, auth
Fosite
Extensible security first OAuth 2.0 and OpenID Connect SDK for Go.
Stars: ✭ 1,738 (+1348.33%)
Mutual labels:  authentication, authorization, auth
Express Graphql Mongodb Boilerplate
A boilerplate for Node.js apps / GraphQL-API / Authentication from scratch - express, graphql - (graphql compose), mongodb (mongoose).
Stars: ✭ 288 (+140%)
Mutual labels:  graphql, authentication, authorization
Rbac
Hierarchical Role Based Access Control for NodeJS
Stars: ✭ 857 (+614.17%)
Mutual labels:  authentication, authorization, auth
Authex
Authex is an opinionated JWT authentication and authorization library for Elixir.
Stars: ✭ 73 (-39.17%)
Mutual labels:  authentication, authorization, auth
Sentinel
A framework agnostic authentication & authorization system.
Stars: ✭ 1,354 (+1028.33%)
Mutual labels:  authentication, authorization, auth
Firebase Functions Graphql Example
GraphQL server running on Cloud Functions for Firebase
Stars: ✭ 107 (-10.83%)
Mutual labels:  graphql, graphql-server
Simpleacl
Simple ACL for PHP
Stars: ✭ 105 (-12.5%)
Mutual labels:  authorization, auth
Graphql Pundit
Pundit authorization helpers for the GraphQL Ruby gem
Stars: ✭ 109 (-9.17%)
Mutual labels:  graphql, authorization

graphql-directive-auth

Version downloads PRs Welcome MIT License

Introduction

The graphql-directive-auth was created to help with common authentication tasks that is faced in almost every API.

Table of Contents

Installation

yarn add graphql-directive-auth

Usage

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';
// or
const AuthDirective = require('graphql-directive-auth').AuthDirective;

// set environment variable, but in better way ;)
process.env.APP_SECRET = 'your_secret_key';

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
  schemaDirectives: {
    // to use @hasRole and @isAuthenticated directives
    ...AuthDirective(),
    // custom name for @isAuthenticated
    auth: AuthDirective().isAuthenticated,
    // custom name for @hasRole
    role: 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 property
  return {
    user: {
      id: 'your_user_id',
    },
  };
};

usage:

import { AuthDirective } from 'graphql-directive-auth';
// or
const AuthDirectives = require('graphql-directive-auth').AuthDirective;

const customAuth = AuthDirectives({
  authenticateFunc: authenticateCustomFunc,
  checkRoleFunc: checkRoleCustomFunc
});

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
  schemaDirectives: {
    // to use @hasRole and @isAuthenticated directives
    ...customAuth,
    // custom name for @isAuthenticated
    auth: customAuth().isAuthenticated,
    // custom name for @hasRole
    role: customAuth().hasRole,
  },

resolver:

export default {
  Query: {
    me() (root, args, ctx){
      const userId = ctx.auth.user.id; // your_user_id
    },
  },
};

Custom check role function

Same as with the authenticate function, you can add your own logic to checking roles. Here is an example of implementation:

import { AuthenticationError } from 'apollo-server';
import jwt from 'jsonwebtoken';
import { jwtSecret } from '../config';

export default (ctx, value) => {
  const authorization =
    ctx.request && ctx.request.headers && ctx.request.headers.authorization;

  if (!authorization) {
    throw new AuthenticationError('Unauthorized access!');
  }

  const token = authorization.replace('Bearer ', '');

  const decodedToken = jwt.verify(token, jwtSecret);

  const mandatoryRoles = value.split(',').map((s) => s.trim());

  if (decodedToken && decodedToken.user && decodedToken.user.roles) {
    const { roles } = decodedToken.user;
    const rolesIntersection = roles.filter((role) =>
      mandatoryRoles.includes(role),
    );

    if (rolesIntersection.length === 0) {
      throw new AuthenticationError('Invalid role!');
    }

    return rolesIntersection;
  }

  throw new AuthenticationError('Invalid token!');
};

How to create your own function

  • Function accepts two parameters, one is the context and the second is the value from the directive
  • To reject an access to the particular field, you need to throw an Error that will be caught by the directive and returned if required.
  • Function doesn't need to return anything special

Directive Parameters

  • '@isAuthenticated' - checks if user is authenticated
  • '@hasRole(role: "user, admin")' - checks if user is authenticated and has the specified roles

if you use graphql-import then you need to add this definition on top of the schema:

directive @isAuthenticated on FIELD | FIELD_DEFINITION
directive @hasRole(role: String) on FIELD | FIELD_DEFINITION

Contributing

I would love to see your contribution. ❤️

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 🎉

Run yarn test (try --watch flag) for unit tests (we are using Jest)

LICENSE

The MIT License (MIT) 2018 - Luke Czyszczonik - mailto:[email protected]

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].