DEV Community

Matteo Kovačić for Bornfight

Posted on

13 4

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.

Query:
  type: object
  config:
    fields:
      activityLog:
        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.

Query:
  type: object
  config:
    fields:
      user:
        type: 'User'
        access: "@=isGranted('user_access', args['id'])"
        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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay