graphql-ruby字段级授权咨询:如何限制UserType指定字段访问?
Absolutely! You can absolutely add field-level authorization directly via the field helper in graphql-ruby—no need to limit yourself to object-wide restrictions. Here are a few straightforward ways to implement this for your UserType field:
1. Inline Authorization Lambda
The simplest approach is to pass an authorize lambda directly to the field definition. This lambda receives the object being resolved, query arguments, and context (where you’ll typically have the current user) to evaluate access:
class UserType < GraphQL::Schema::Object field :id, ID, null: false field :name, String, null: false # Add authorization to the sensitive field field :secret_field, String, null: true, authorize: ->(user, args, ctx) { # Your custom logic here—e.g., allow admins or the user themselves ctx[:current_user].present? && (ctx[:current_user].admin? || ctx[:current_user].id == user.id) } end
If the lambda returns false, graphql-ruby will automatically throw an authorization error, and the field won’t be resolved.
2. Reusable Authorizer Class
If you want to reuse this authorization logic across multiple fields, create a dedicated authorizer class with an authorized? class method:
class SecretFieldAuthorizer def self.authorized?(user, args, ctx) ctx[:current_user].present? && (ctx[:current_user].admin? || ctx[:current_user].id == user.id) end end
Then reference it in your field definition:
class UserType < GraphQL::Schema::Object # ... other fields field :secret_field, String, null: true, authorize: SecretFieldAuthorizer end
3. Manual Check in Resolve
You can also handle authorization directly in the field's resolve block if you need more control over error handling (e.g., returning nil instead of throwing an error):
class UserType < GraphQL::Schema::Object # ... other fields field :secret_field, String, null: true do resolve ->(user, args, ctx) { unless ctx[:current_user].present? && (ctx[:current_user].admin? || ctx[:current_user].id == user.id) # Option 1: Raise an explicit error raise GraphQL::ExecutionError, "You are not authorized to access this field" # Option 2: Return nil silently # nil end user.secret_field } end end
Quick Notes
- Ensure your context (
ctx) is populated with the current user (usually set up in your schema’s query context configuration). - The syntax works for most recent graphql-ruby versions (1.10+); minor adjustments may apply for older releases.
- Authorization failures will appear in the GraphQL response’s
errorsarray unless you opt to returnnilinstead of raising an error.
内容的提问来源于stack exchange,提问作者Such

