OAuth2 and OpenID Connect (OIDC) are the industry standard protocols for delegated authentication — “Login with Google” is OIDC, and API tokens are OAuth2. Self-hosting an OAuth2/OIDC identity server on your Hong Kong VPS gives your organisation full control over user authentication, enables single sign-on (SSO) across multiple applications, and keeps user identity data in your jurisdiction rather than a US SaaS provider’s infrastructure — an increasingly important consideration for Asia-Pacific businesses subject to PDPO or regional data laws.
Ory Hydra: Production-Grade OAuth2 Server
Ory Hydra is a hardened, OpenID Connect certified OAuth2 server — not a full identity provider (no user management UI), but a pure protocol implementation that integrates with your existing user database. It handles token issuance, introspection, and revocation while delegating login UI to your application.
Step 1: Deploy Ory Hydra
<code">apt update && apt install -y docker.io docker-compose-plugin mkdir -p /opt/hydra/config # Generate secrets SYSTEM_SECRET=$(openssl rand -hex 32) COOKIE_SECRET=$(openssl rand -hex 32) cat > /opt/hydra/.env << EOF DSN=postgres://hydra_user:HydraPass!@localhost/hydra_db SECRETS_SYSTEM=$SYSTEM_SECRET SECRETS_COOKIE=$COOKIE_SECRET URLS_SELF_ISSUER=https://auth.yourdomain.com/ URLS_LOGIN=https://yourdomain.com/login URLS_CONSENT=https://yourdomain.com/consent URLS_LOGOUT=https://yourdomain.com/logout SERVE_PUBLIC_CORS_ENABLED=true SERVE_PUBLIC_CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com LOG_LEVEL=info LOG_FORMAT=json TTL_ACCESS_TOKEN=1h TTL_REFRESH_TOKEN=720h # 30 days TTL_ID_TOKEN=1h TTL_AUTH_CODE=10m EOF # Create PostgreSQL database for Hydra sudo -u postgres psql << 'SQL' CREATE USER hydra_user WITH PASSWORD 'HydraPass!'; CREATE DATABASE hydra_db OWNER hydra_user; SQL # Download Hydra binary wget https://github.com/ory/hydra/releases/latest/download/hydra_linux_amd64.tar.gz tar xzf hydra_linux_amd64.tar.gz -C /usr/local/bin/ chmod +x /usr/local/bin/hydra # Run database migrations export $(cat /opt/hydra/.env | xargs) hydra migrate sql --yes "$DSN"
Systemd Services
<code">cat > /etc/systemd/system/hydra-public.service << 'EOF' [Unit] Description=Ory Hydra Public API After=network.target postgresql.service [Service] EnvironmentFile=/opt/hydra/.env ExecStart=/usr/local/bin/hydra serve public --config /opt/hydra/config/hydra.yaml Restart=always [Install] WantedBy=multi-user.target EOF cat > /etc/systemd/system/hydra-admin.service << 'EOF' [Unit] Description=Ory Hydra Admin API After=network.target postgresql.service [Service] EnvironmentFile=/opt/hydra/.env ExecStart=/usr/local/bin/hydra serve admin --config /opt/hydra/config/hydra.yaml Restart=always [Install] WantedBy=multi-user.target EOF systemctl enable --now hydra-public hydra-admin
Step 2: Nginx for Public Endpoint
<code">cat > /etc/nginx/sites-available/hydra << 'EOF'
# Public OIDC endpoint — accessible by clients
server {
listen 443 ssl http2;
server_name auth.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/auth.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/auth.yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:4444; # Hydra public port
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Real-IP $remote_addr;
}
}
# Admin API — restrict to VPN/local
server {
listen 127.0.0.1:4445; # Admin only accessible locally
location / {
proxy_pass http://127.0.0.1:4445;
}
}
EOF
certbot --nginx -d auth.yourdomain.com
nginx -t && systemctl reload nginx
Step 3: Register OAuth2 Clients
<code"># Register a client application hydra clients create \ --endpoint http://localhost:4445 \ # Admin endpoint --id my-frontend-app \ --name "My Frontend Application" \ --secret ClientSecret123! \ --grant-types authorization_code,refresh_token \ --response-types code \ --scope openid,offline_access,profile,email \ --callbacks https://yourdomain.com/callback \ --post-logout-callbacks https://yourdomain.com/logout/callback \ --token-endpoint-auth-method client_secret_basic # Machine-to-machine (service account) hydra clients create \ --endpoint http://localhost:4445 \ --id api-service \ --name "Internal API Service" \ --secret ApiSecret456! \ --grant-types client_credentials \ --scope api:read,api:write # Verify hydra clients list --endpoint http://localhost:4445
Step 4: Implement Login and Consent (Node.js)
<code"># Your application handles the login UI — Hydra delegates to you
# npm install @ory/client express express-session
const { Configuration, OAuth2Api } = require('@ory/client')
const hydraAdmin = new OAuth2Api(new Configuration({
basePath: 'http://localhost:4445', // Hydra admin — internal only
}))
// Login endpoint — called by Hydra when user needs to authenticate
app.get('/login', async (req, res) => {
const { login_challenge } = req.query
// Get login request details from Hydra
const { data: loginRequest } = await hydraAdmin.getOAuth2LoginRequest({
loginChallenge: login_challenge,
})
// If user is already authenticated (Hydra has a session), skip login
if (loginRequest.skip) {
const { data: acceptResponse } = await hydraAdmin.acceptOAuth2LoginRequest({
loginChallenge: login_challenge,
acceptOAuth2LoginRequest: { subject: loginRequest.subject },
})
return res.redirect(acceptResponse.redirect_to)
}
// Show login form
res.render('login', { challenge: login_challenge, error: req.query.error })
})
// Handle login form submission
app.post('/login', async (req, res) => {
const { challenge, email, password } = req.body
// Authenticate against YOUR user database
const user = await db.query(
'SELECT id, email FROM users WHERE email = $1 AND password_hash = crypt($2, password_hash)',
[email, password]
)
if (!user.rows.length) {
return res.redirect(`/login?challenge=${challenge}&error=Invalid credentials`)
}
// Tell Hydra login succeeded
const { data } = await hydraAdmin.acceptOAuth2LoginRequest({
loginChallenge: challenge,
acceptOAuth2LoginRequest: {
subject: user.rows[0].id.toString(),
remember: true,
remember_for: 3600, // 1 hour
acr: '0',
},
})
res.redirect(data.redirect_to)
})
// Consent endpoint — user grants permissions to the OAuth2 client
app.get('/consent', async (req, res) => {
const { consent_challenge } = req.query
const { data: consentRequest } = await hydraAdmin.getOAuth2ConsentRequest({
consentChallenge: consent_challenge,
})
// Auto-accept consent for trusted first-party apps
if (consentRequest.client?.metadata?.first_party) {
const { data } = await hydraAdmin.acceptOAuth2ConsentRequest({
consentChallenge: consent_challenge,
acceptOAuth2ConsentRequest: {
grant_scope: consentRequest.requested_scope,
grant_access_token_audience: consentRequest.requested_access_token_audience,
remember: true,
remember_for: 86400,
session: {
id_token: {
email: consentRequest.subject + '@yourdomain.com',
// Add custom claims here
}
}
},
})
return res.redirect(data.redirect_to)
}
// Show consent UI for third-party clients
res.render('consent', { challenge: consent_challenge, request: consentRequest })
})
Step 5: Validate Tokens in Your APIs
<code"># APIs validate tokens via Hydra's introspection endpoint
async function validateToken(token) {
const { data } = await hydraAdmin.introspectOAuth2Token({
token,
scope: 'api:read', // Required scope for this endpoint
})
if (!data.active) throw new Error('Token expired or revoked')
return data // Contains: sub (user ID), scope, exp, etc.
}
// Express middleware
async function requireAuth(scope) {
return async (req, res, next) => {
const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) return res.status(401).json({ error: 'No token' })
const tokenData = await validateToken(token)
req.user = tokenData
next()
}
}
// Protected route
app.get('/api/profile', requireAuth('profile'), async (req, res) => {
const user = await db.query('SELECT * FROM users WHERE id = $1', [req.user.sub])
res.json(user.rows[0])
})
# Client credentials (M2M tokens):
const response = await fetch('https://auth.yourdomain.com/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: 'api-service',
client_secret: 'ApiSecret456!',
scope: 'api:read api:write',
})
})
const { access_token } = await response.json()
Well-Known OIDC Discovery
<code"># Standard OIDC discovery endpoint (clients use this to find token/auth endpoints)
curl https://auth.yourdomain.com/.well-known/openid-configuration
# Returns:
{
"issuer": "https://auth.yourdomain.com/",
"authorization_endpoint": "https://auth.yourdomain.com/oauth2/auth",
"token_endpoint": "https://auth.yourdomain.com/oauth2/token",
"jwks_uri": "https://auth.yourdomain.com/.well-known/jwks.json",
"userinfo_endpoint": "https://auth.yourdomain.com/userinfo",
"response_types_supported": ["code"],
"subject_types_supported": ["public"],
"id_token_signing_alg_values_supported": ["RS256"]
}
Conclusion
Ory Hydra on a Hong Kong VPS provides an OpenID Connect certified OAuth2 server for Asia-Pacific deployments — user identity stays on your infrastructure in Hong Kong’s jurisdiction, SSO works across all your applications, and the protocol implementation handles token issuance and validation correctly without writing your own OAuth2 logic. For organisations subject to PDPO (Hong Kong) or PDPA (Singapore), keeping identity infrastructure on your own VPS rather than a US SaaS provider gives clearer data governance answers to regulatory questions.
Own your authentication: Browse Server.HK Hong Kong VPS plans — a 2 GB plan comfortably runs Ory Hydra alongside your PostgreSQL database for most identity server workloads.