Authorization is part of almost any web application and controlling access to specific data is essential for application security. The same goes for GraphQL APIs and with help of Overblog's GraphQL Bundle, this can be done easily.
Field access control
Every GraphQL API has at least one root type, Query. Root types are the most common place where we would want to control access by setting rules to a specific field. Some examples could be controlling access to some admin-related queries by allowing only users with ROLE_ADMIN
role or allowing access to user
query only if a requested user is currently authenticated user or has ROLE_ADMIN
role. This can be done using expression language functions in the field configuration option called resolve
.
Using hasRole
This expression language function is provided by the bundle and is self-explanatory - it checks if the currently authenticated user has the role you provide as an argument.
Query:
type: object
config:
fields:
activityLog:
type: "[Activity!]!"
access: "@=hasRole('ROLE_ADMIN')"
resolve: "@=resolver('ActivityLog')"
Using isGranted
This function is not documented in the official documentation, but it actually exists if you look closely in the codebase. Sometimes checking role is not sufficient and we want complex logic to determine if a user has access or not. This can be done using voters and isGranted
expression language function.
Query:
type: object
config:
fields:
user:
type: 'User'
access: "@=isGranted('user_access', args['id'])"
args:
id:
type: 'ID!'
resolve: "@=resolver('User', [args['id']])"
If you have any questions, comments or experiences with using GraphQL you'd like to share, put them in the comments section below!
Top comments (0)