The GraphQL API is protected by a role-based permission system based on access tokens. Permissions are handled on a per-table basis in Hasura Console.
Upon login a user gets an access token which is then being sent with every GraphQL API request to authenticate the user and apply the correct permissions when reading and writing data.
In Hasura you can specify what a user is allowed to do. A common use case is to allow a user to read something if
user_id in the database is equal to the user ID in the access token.
Access token data is included as headers with every API request. By default, every user has the following session variables that can be used when creating permission rules:
The default role for users is
One of the most common permission requirements is that logged-in users should only be able to read their own data. This is how it can be achieved with Hasura.
- Go to Hasura Console
- Select your table and open the Permissions tab
- At the top of the page, click "select" on the "user" role.
- Select "With custom check" to create a new rule
x-hasura-user-id into the rule form.
This means that in order for users to read data, the user ID value in the database row must be the same as the user ID in the access token.
To further refine this rule, do the following:
- Limit number of rows to 100 (or some other relevant number).
- Select the columns you want the user to be able to read. In our case we'll allow the user to read all columns.
Note that if you add columns to your table table later, you must check new columns here to let users read them.
Here is a popular approach for insert permission for logged in users.
- At the top of the page, click "insert" on the "user" role.
- Select "Without any checks".
- Select the columns you want to allow users to insert.
In our example, we only select
name, because we want all other other columns to be filled with default values.
We also want every new record's
user_id value to be set to the ID of the user making the request. We can tell Hasura to do this with column presets.
- Under column presets, set