• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

graphql-community/graphql-directive-auth: GraphQL directive for handling auth

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

graphql-community/graphql-directive-auth

开源软件地址(OpenSource Url):

https://github.com/graphql-community/graphql-directive-auth

开源编程语言(OpenSource Language):

TypeScript 92.0%

开源软件介绍(OpenSource Introduction):

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
zhaiqianfeng/GraphQL-Demo: 用于博文演示GraphQL相关操作发布时间:2022-06-22
下一篇:
logaretm/villus: 发布时间:2022-06-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap