Authentication overview
Hasura provides an instant GraphQL API over new or existing databases, requiring robust authentication to secure data access. Authentication in Hasura primarily involves verifying the identity of a client (user or service) before allowing them to interact with the GraphQL API. This process determines who is making a request, while authorization (often integrated with authentication) determines what actions that identified client is permitted to perform.
Hasura supports several authentication mechanisms, allowing developers to choose the method best suited for their application's security requirements and existing infrastructure. These methods range from simple admin secrets for development and internal tools to more sophisticated JSON Web Token (JWT) and webhook-based approaches for production-grade applications that integrate with external identity providers. The goal is to ensure that every request to the Hasura GraphQL Engine is validated against defined security policies, protecting the underlying data sources.
The Hasura GraphQL Engine processes incoming requests and uses the provided authentication credentials to identify the user and apply relevant authorization rules. This enables granular control over data access, including row-level and column-level permissions, ensuring that users only interact with data they are authorized to see or modify. For detailed information on how Hasura processes authentication and authorization, refer to the official Hasura authentication overview documentation.
Supported authentication methods
Hasura offers a flexible set of authentication methods to accommodate various application architectures and security models. Each method has specific use cases and implications for deployment and security. Choosing the right method depends on factors such as integration with existing identity providers, the need for custom logic, and the scale of the application.
The primary authentication methods supported by Hasura are:
- Admin Secret Key: This is a powerful, single secret key that grants full administrative access to the Hasura GraphQL Engine. It bypasses all authorization rules and should be used with extreme caution. It is suitable for development environments, internal tools, or when configuring Hasura itself, but never for client-facing applications.
- JSON Web Tokens (JWT): JWTs are a common method for securely transmitting information between parties as a JSON object. Hasura can be configured to validate JWTs issued by external identity providers (IdPs) such as Auth0, Firebase, AWS Cognito, or any custom OAuth 2.0 / OpenID Connect compatible service. JWTs contain claims (e.g., user ID, roles) that Hasura uses to apply authorization rules. This method provides stateless authentication and is highly scalable. The JWT.io introduction provides an overview of JWT structure and usage.
- Webhook-based Authentication: For scenarios requiring custom authentication logic or integration with an existing, non-JWT identity system, Hasura supports webhook-based authentication. In this setup, Hasura sends the incoming request's headers and other relevant information to a custom HTTP endpoint (the webhook). The webhook service then validates the request and returns a JSON response containing user roles and session variables, which Hasura uses for authorization. This offers maximum flexibility for integrating with any authentication system.
Here's a comparison of Hasura's authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| Admin Secret Key | Development, internal tools, server-to-server communication, Hasura Console access. | High privilege, requires strict protection. Not for client-side use. |
| JSON Web Tokens (JWT) | Client-facing applications, integration with OAuth/OIDC providers (Auth0, Firebase, etc.), stateless authentication. | High, relies on secure token issuance and validation. |
| Webhook-based Authentication | Custom authentication logic, integration with proprietary identity systems, complex authorization requirements. | Configurable, depends on the security of the custom webhook service. |
Getting your credentials
The process for obtaining and configuring authentication credentials in Hasura varies by the chosen method:
Admin Secret Key
When deploying Hasura, you typically set the admin secret key as an environment variable. For Hasura Cloud, this is configured during project creation or via the project settings. For self-hosted deployments, you would set the HASURA_GRAPHQL_ADMIN_SECRET environment variable. You can view and manage this secret within the Hasura Cloud console under Project Settings > Env Vars. Always treat this key as highly sensitive, similar to a database root password.
JWT Configuration
To use JWT authentication, you need to configure Hasura to validate tokens issued by your identity provider. This involves:
- Obtaining the JWT public key or JWKS endpoint: Your identity provider (e.g., Auth0, Firebase, AWS Cognito) will provide a public key or a JSON Web Key Set (JWKS) endpoint. Hasura uses this to verify the signature of incoming JWTs. For example, Firebase provides documentation on verifying ID tokens.
- Configuring Hasura: You set environment variables for Hasura to point to your JWT configuration. Key variables include
HASURA_GRAPHQL_JWT_SECRET, which defines the type of JWT secret (e.g.,HS256,RS256), the JWKS URL, and other parameters like allowed algorithms and issuer. This can be done in the Hasura Cloud console or via environment variables in a self-hosted setup. - Client-side token acquisition: Your client application (web, mobile, backend) will interact with your identity provider to obtain a JWT. This token is then sent with every request to Hasura in the
Authorizationheader, typically as a Bearer token.
Webhook Configuration
For webhook-based authentication, you must:
- Develop a custom authentication webhook: This is an HTTP endpoint that receives request headers from Hasura, validates them, and returns a JSON response. The response must contain
X-Hasura-User-Id(or similar) andX-Hasura-Roleheaders, along with any other session variables required for authorization. - Configure Hasura: Set the
HASURA_GRAPHQL_AUTH_HOOKenvironment variable to the URL of your webhook endpoint. Hasura will then forward authentication requests to this URL. - Secure the webhook: Ensure your webhook endpoint is protected (e.g., via IP whitelisting, shared secret headers) to prevent unauthorized access.
Refer to the Hasura webhook authentication documentation for detailed implementation steps.
Authenticated request example
Here's an example of a GraphQL query to a Hasura endpoint, authenticated using a JWT. The client obtains a JWT from an identity provider and includes it in the Authorization header.
POST /v1/graphql HTTP/1.1
Host: your-hasura-instance.hasura.app
Content-Type: application/json
Authorization: Bearer <YOUR_JWT_TOKEN>
{
"query": "query GetUsers { users { id name email } }"
}
In this example:
<YOUR_JWT_TOKEN>is the actual JWT issued by your identity provider.- Hasura receives this request, validates the JWT's signature and claims against its configuration, extracts session variables (like
X-Hasura-User-IdandX-Hasura-Role) from the token, and then applies the appropriate authorization rules before executing theGetUsersquery.
Security best practices
Implementing strong authentication is critical for securing a Hasura-powered application. Adhering to security best practices helps protect your data from unauthorized access and potential vulnerabilities.
- Never expose Admin Secret Key publicly: The admin secret grants full access. It should never be hardcoded in client-side code or exposed in public repositories. Use environment variables for server-side applications and strict access controls for internal tools.
- Use JWTs for client-facing applications: For user authentication, JWTs combined with an industry-standard identity provider (like Auth0, Firebase, or AWS Cognito) offer a secure and scalable solution. Ensure your JWTs have short expiration times and are refreshed securely.
- Implement robust authorization: While authentication verifies identity, authorization restricts what an identified user can do. Leverage Hasura's powerful Role-Based Access Control (RBAC) to define granular permissions, including row-level and column-level security. Define roles carefully and assign users the minimum necessary privileges.
- Secure your JWT secrets/keys: If you are self-managing JWT secrets (e.g., using symmetric keys), ensure they are strong, unique, and stored securely. For asymmetric keys, protect your private key diligently.
- Validate all input: Beyond authentication, always validate and sanitize all incoming data to prevent common vulnerabilities like SQL injection or cross-site scripting (XSS), even though Hasura's GraphQL layer provides some inherent protection.
- Protect webhook endpoints: If using webhook authentication, ensure your webhook endpoint is secured. Use HTTPS, implement IP whitelisting, and consider using a shared secret to verify that requests to the webhook originate from your Hasura instance.
- Regularly rotate credentials: Periodically change your admin secrets, JWT signing keys, and any other sensitive credentials.
- Monitor and log access: Implement logging for authentication attempts and API access. Monitor these logs for suspicious activity, such as repeated failed login attempts or unusual access patterns.
- Stay updated: Keep your Hasura GraphQL Engine and any related authentication services updated to the latest stable versions to benefit from security patches and improvements.
- Implement HTTPS/SSL: Always ensure all communication with your Hasura instance and authentication services occurs over HTTPS to encrypt data in transit and prevent eavesdropping.
By combining these practices, developers can build secure and reliable applications on the Hasura platform, protecting sensitive data and ensuring only authorized interactions with their GraphQL APIs. The Hasura security overview provides further guidance on securing your deployment.