如何选择性地允许 apollo-server-express 中的查询?

Posted

技术标签:

【中文标题】如何选择性地允许 apollo-server-express 中的查询?【英文标题】:How to selectively allow queries in apollo-server-express? 【发布时间】:2020-09-09 20:50:12 【问题描述】:

我的服务器正在处理的大多数查询和突变都需要授权。但是,有一些解析器应该是公开的,即登录、注册、忘记密码。我怎样才能有选择地允许这些解析被命中并且默认情况下对其余的有一个授权门?

目前正在使用 apollo-server-express 和 type-graphql。

【问题讨论】:

【参考方案1】:

您好,您可以在架构定义上使用 @Authorized() 装饰器和 authChecker 函数,

这里是示例代码

import  Request  from "express";
import  ApolloServer,  from "apollo-server-express";
          
export interface ExpressContext 
  req: Request;


export const userAuthChecker: AuthChecker<ExpressContext> = async (
   root, args, context:  req , info ,
  roles,
) => 
  //Perform your own logic here 
  return false; // true if the user is authorized   
;

  // Add your Auth checker middleware to your buildSchema method
const schema = await buildSchema(
  
    authChecker: userAuthChecker,
    resolvers: [...yourresolvers]
  
);

// then define your context from the apollo server setup
const apolloserver = new ApolloServer(
  schema, context: (ctx) => 
    return ctx;
  
);

// After Completing the above this is how you put it in action, with @Authorized() // decorator
@ObjectType()
export class Resolver extends BaseEntity 
  ...
  @Authorized('Admin') // <---
  @Query(returns => [MyModel])
  artists() 
    return value;
  )


【讨论】:

以上是关于如何选择性地允许 apollo-server-express 中的查询?的主要内容,如果未能解决你的问题,请参考以下文章

如何允许 DIV 的文本选择,但阻止父 DIV 的文本选择?

如何允许 DIV 的文本选择,但阻止父 DIV 的文本选择?

jQuery 选择器

Select2:如何允许用户从默认列表中选择但接受新字符串?

jQuery 选择器

如何使用 UIApplication.shared.open 在 iOS 上选择性地打开其他应用程序