Skip to content

Enforcing authorization over GraphQL Queries

Bff modules depend on GraphQLGatewayModule by default. This is enough for configuring Suite Authorization directive and middleware, yet, we still need to provide a resolver to validate against.

We do so by depending on Rbac Authorization Module from our Bff module.

C#
builder.DependsOn<RbacAuthorizationModule>()

Once our Bff and federations are properly configured, we can apply authorization over our exposed query if we want to restrict access to a certain type of users.

In order to do so, head to your EMA.extensions.graphql file and add the @suiteAuthorize directive in the extended type, just like we did with the @delegate directive.

GraphQL
extend type Query {
  equipments(
    first: Int
    after: String
    last: Int
    before: String
    where: EquipmentInput
    order: [EquipmentSortInput!]
  ): EquipmentsConnection @delegate() @suiteAuthorize(permissions: "suite/equipments/read")
}

Authorization middleware will now validate the required permission against the current user's permissions.

You can check this by heading to the playground and attempting to execute the query. A response with an error payload will be returned.

JSON
{
    "errors": [
        {
            "message": "The current user is not authorized to access this resource.",
            "locations": [
                {
                    "line": 2,
                    "column": 3
                }
            ],
            "path": ["equipments"],
            "extensions": {
                "code": "AUTH_NOT_AUTHENTICATED"
            }
        }
    ],
    "data": {
        "equipments": null
    }
}

The error code varies depending on the failure reason:

  • AUTH_NOT_AUTHENTICATED: No token has been attached to the request. Check GraphQL Authentication for more details on how to authenticate a playground query.

  • AUTH_NOT_AUTHORIZED: User is authenticated, but has no permissions to access this resource. By default, Admin Users are granted full control over all resources. All other default users (or newly created ones) have no permissions assigned from scratch.

Additionally, an exception will be raised if you provide an invalid permission name when configuring your GraphQL types. As a first validation measure, Rbac verifies that all the required permissions are persisted in the database.

If you want further detail on access management you can check Suite RBAC documentation.