[英]Authorization on a field in graphql-ruby
從本指南中,我不明白我們如何在 graphql-ruby 中的字段上添加授權。
我了解我們如何拒絕訪問整個對象,但我不明白我們如何阻止僅訪問對象的一個字段。 在我的用例中,我想阻止某些查詢訪問我的UserType
的String
field
。
是否可以? 與field
幫手?
您可以在GraphQL-ruby中使用作用域 ,也可以使用gem graphql-guard 。
對於作用域的工作,你應該是使用權威人士范圍或慘慘accessible_by 。
僅供參考,我還沒有在任何地方使用它,但是似乎兩者都可以解決您的問題。
我使用了gem graphql-guard 。
GUARD = lambda do |obj, args, ctx|
...some logics...
end
field :some_field, String, null: false, guard: GUARD
當我只想使用lambda do |_, args, _|
之類的參數時lambda do |_, args, _|
下面是一個例子:
module Types
class User < Types::BaseObject
field :private_string, String, null: true do
def authorized?(object, args, context)
# Do whatever logic you want and return true if the user is authorized.
object.id == context[:current_user].id
end
end
end
end
class MySchema < GraphQL::Schema
# You'll need this in your schema to handle an unauthorized field.
def self.unauthorized_field(error)
raise GraphQL::ExecutionError, "The field #{error.field.graphql_name} on an object of type #{error.type.graphql_name} was hidden due to permissions"
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.