DEV Community

Matteo Kovačić for Bornfight

Posted on

Access control in GraphQL using Symfony

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.

  type: object
        type: "[Activity!]!"
        access: "@=hasRole('ROLE_ADMIN')"
        resolve: "@=resolver('ActivityLog')"
Enter fullscreen mode Exit fullscreen mode

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.

  type: object
        type: 'User'
        access: "@=isGranted('user_access', args['id'])"
            type: 'ID!'
        resolve: "@=resolver('User', [args['id']])"
Enter fullscreen mode Exit fullscreen mode

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)