# Ory Hydra

> OAuth 2.0 and OpenID Connect provider.

- Category: Security & Networking
- Difficulty: advanced
- Components: hydra, postgres
- Tags: ory, hydra, oauth, oidc
- Source: https://docker.recipes/security/ory-hydra

## Overview

Ory Hydra is a hardened, cloud-native OAuth 2.0 and OpenID Connect server that implements the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0. Developed by Ory Corp as part of their open-source identity infrastructure ecosystem, Hydra is designed as a security-first authorization server that handles token issuance, client authentication, and consent flows while delegating user authentication to external systems. Unlike monolithic identity solutions, Hydra follows a microservices architecture where it focuses solely on OAuth2/OIDC protocols, making it highly scalable and integration-friendly for modern distributed applications.

This deployment combines Ory Hydra with PostgreSQL to create a production-grade authorization infrastructure. PostgreSQL serves as Hydra's persistence layer, storing OAuth2 clients, authorization codes, access tokens, refresh tokens, and OIDC sessions with ACID compliance and advanced transaction support. The PostgreSQL backend ensures data integrity for security-critical operations while providing the performance characteristics needed for high-throughput token operations. Hydra exposes two distinct APIs: the public OAuth2 API on port 4444 for standard authorization flows and token endpoints, and the administrative API on port 4445 for client management and token introspection.

This stack is ideal for organizations implementing zero-trust architectures, API-first companies requiring centralized authorization, and development teams building microservices that need robust OAuth2/OIDC capabilities. The separation of concerns between Hydra's authorization logic and external authentication systems makes it particularly valuable for enterprises with existing identity providers or custom authentication requirements. The PostgreSQL backend ensures this configuration can handle enterprise-scale workloads while maintaining the security guarantees required for authorization infrastructure.

## Features

- RFC-compliant OAuth 2.0 Authorization Server with support for all standard grant types including authorization code, client credentials, and refresh token flows
- OpenID Connect Provider implementation with support for ID tokens, userinfo endpoint, and discovery mechanisms
- Dual-port architecture with separate public OAuth2 API (4444) and administrative API (4445) for security isolation
- PostgreSQL-backed persistence with ACID-compliant storage for OAuth2 clients, tokens, and authorization grants
- Consent and login flow delegation allowing integration with existing authentication systems and custom user interfaces
- Advanced token introspection and revocation capabilities through the administrative API
- Built-in support for JWT access tokens with configurable signing algorithms and key rotation
- Database migration system ensuring schema versioning and upgrade compatibility across Hydra releases

## Use cases

- API gateway authorization for microservices architectures requiring centralized OAuth2 token validation
- Single sign-on (SSO) implementation for multi-application environments with existing user authentication systems
- Third-party application integration hub allowing external developers to build applications against your APIs
- Zero-trust network security implementation where every service-to-service communication requires valid OAuth2 tokens
- Mobile application backend providing secure token-based authentication for iOS and Android applications
- Enterprise B2B integration platform enabling partner applications to access internal APIs through standardized OAuth2 flows
- Multi-tenant SaaS platform requiring isolated OAuth2 clients and scopes for different customer organizations

## Prerequisites

- Minimum 1GB RAM for PostgreSQL database operations and Hydra token processing
- Available ports 4444 (OAuth2 public API) and 4445 (administrative API) for external access
- Separate login and consent application implementation as Hydra delegates user authentication flows
- Understanding of OAuth 2.0 authorization flows and OpenID Connect concepts for proper client configuration
- TLS certificate management knowledge for production deployments requiring HTTPS endpoints
- Database backup and recovery procedures for protecting OAuth2 client credentials and token data

## docker-compose.yml

```yaml
services:
  hydra:
    image: oryd/hydra:latest
    container_name: hydra
    restart: unless-stopped
    environment:
      DSN: postgres://hydra:${DB_PASSWORD}@postgres:5432/hydra?sslmode=disable
      SECRETS_SYSTEM: ${SECRETS_SYSTEM}
      URLS_SELF_ISSUER: http://localhost:4444
      URLS_LOGIN: http://localhost:3000/login
      URLS_CONSENT: http://localhost:3000/consent
    command: serve all --dev
    ports:
      - "4444:4444"
      - "4445:4445"
    depends_on:
      - postgres

  postgres:
    image: postgres:15-alpine
    container_name: hydra-db
    environment:
      POSTGRES_USER: hydra
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: hydra
    volumes:
      - hydra_db:/var/lib/postgresql/data

volumes:
  hydra_db:
```

## .env

```bash
DB_PASSWORD=changeme
SECRETS_SYSTEM=generate-32-char-secret
```

## Usage notes

- Docs: https://www.ory.sh/docs/hydra/
- Public OAuth2 API on port 4444 (token, authorize endpoints)
- Admin API on port 4445 (client management, introspection)
- Requires separate login/consent UI - Hydra handles only OAuth2 flows
- Create clients: hydra create oauth2-client --endpoint http://localhost:4445
- Run migrations first: hydra migrate sql --yes $DSN

## Troubleshooting

- Error 'migration required': Run 'docker exec hydra hydra migrate sql --yes $DSN' to initialize or upgrade database schema
- Connection refused on port 4444/4445: Check that Hydra container started successfully and PostgreSQL connection is established before Hydra initialization
- Login flow errors with 'invalid_request': Verify URLS_LOGIN and URLS_CONSENT environment variables point to accessible login/consent applications
- Database connection errors: Ensure PostgreSQL container is fully initialized before Hydra starts using depends_on and health checks
- Token validation failures: Confirm URLS_SELF_ISSUER matches the issuer claim expected by resource servers validating tokens
- Client creation fails: Use administrative API on port 4445 with proper authentication headers when creating OAuth2 clients programmatically

