Zum Inhalt

Authentication Anleitung

GAL v1.1.0 führt umfassende Authentication-Unterstützung für alle Gateway-Provider ein. Diese Anleitung erklärt, wie Sie Authentication für Ihre APIs mit Basic Auth, API Keys und JWT konfigurieren.

Inhaltsverzeichnis

Übersicht

Authentication stellt sicher, dass nur autorisierte Benutzer auf Ihre APIs zugreifen können. GAL unterstützt drei Authentication-Methoden:

Typ Anwendungsfall Sicherheitslevel Komplexität
Basic Auth Interne Tools, Admin-Panels Mittel Niedrig
API Key Service-to-Service, Externe APIs Mittel-Hoch Niedrig
JWT Moderne Web/Mobile Apps, Microservices Hoch Mittel

Schnellstart

API Key Authentication (Am einfachsten)

services:
  - name: my_api
    type: rest
    protocol: http
    upstream:
      host: api.local
      port: 8080
    routes:
      - path_prefix: /api/protected
        authentication:
          enabled: true
          type: api_key
          api_key:
            keys:
              - "your-secret-key-123"
            key_name: X-API-Key
            in_location: header

Test mit curl:

curl -H "X-API-Key: your-secret-key-123" http://localhost:10000/api/protected

Basic Authentication

services:
  - name: admin_api
    type: rest
    protocol: http
    upstream:
      host: admin.local
      port: 8080
    routes:
      - path_prefix: /api/admin
        authentication:
          enabled: true
          type: basic
          basic_auth:
            users:
              admin: "super_secret_password"
              operator: "operator_pass"
            realm: "Admin Area"

Test mit curl:

curl -u admin:super_secret_password http://localhost:10000/api/admin

JWT Authentication

services:
  - name: secure_api
    type: rest
    protocol: http
    upstream:
      host: secure.local
      port: 8080
    routes:
      - path_prefix: /api/user
        authentication:
          enabled: true
          type: jwt
          jwt:
            issuer: "https://auth.example.com"
            audience: "api.example.com"
            jwks_uri: "https://auth.example.com/.well-known/jwks.json"
            algorithms:
              - RS256

Test mit curl:

curl -H "Authorization: Bearer YOUR_JWT_TOKEN" http://localhost:10000/api/user

Authentication-Typen

Basic Authentication

HTTP Basic Authentication verwendet Username/Password-Credentials, die in HTTP-Headern übertragen werden.

Konfiguration

authentication:
  enabled: true
  type: basic
  basic_auth:
    users:
      username1: "password1"
      username2: "password2"
    realm: "Protected Area"
  fail_status: 401
  fail_message: "Unauthorized"

Parameter

  • users (dict): Mapping von Benutzername zu Passwort
  • realm (string): Authentication-Realm im Browser-Prompt angezeigt (Standard: "Protected")
  • fail_status (int): HTTP-Statuscode bei Auth-Fehlern (Standard: 401)
  • fail_message (string): Fehlermeldung bei Auth-Fehlern

Sicherheitsüberlegungen

⚠️ Wichtige Sicherheitshinweise: - Passwörter sollten in Production gehasht sein (z.B. bcrypt, htpasswd-Format) - Verwenden Sie immer HTTPS, um Credentials während der Übertragung zu schützen - Speichern Sie niemals Klartext-Passwörter in Konfigurationsdateien - Erwägen Sie die Verwendung von Umgebungsvariablen oder Secrets Management

Production-Beispiel mit htpasswd:

# Generiere htpasswd-Hash
htpasswd -nb admin secret_password

# Ausgabe: admin:$apr1$XYZ123$HASH...
basic_auth:
  users:
    admin: "$apr1$XYZ123$HASH..."  # htpasswd-Format

API Key Authentication

API Key Authentication verwendet statische Keys, die in Headern oder Query-Parametern übergeben werden.

Konfiguration - Header-basiert

authentication:
  enabled: true
  type: api_key
  api_key:
    keys:
      - "key_123abc"
      - "key_456def"
      - "key_789ghi"
    key_name: X-API-Key
    in_location: header

Konfiguration - Query Parameter

authentication:
  enabled: true
  type: api_key
  api_key:
    keys:
      - "key_123abc"
    key_name: api_key
    in_location: query

Verwendung:

# Header-basiert
curl -H "X-API-Key: key_123abc" http://localhost:10000/api

# Query Parameter
curl "http://localhost:10000/api?api_key=key_123abc"

Parameter

  • keys (list): Gültige API Keys
  • key_name (string): Header- oder Query-Parameter-Name (Standard: "X-API-Key")
  • in_location (string): "header" oder "query" (Standard: "header")

Best Practices

Empfohlen: - Verwenden Sie lange, zufällige Keys (mindestens 32 Zeichen) - Rotieren Sie Keys regelmäßig - Verwenden Sie unterschiedliche Keys für verschiedene Clients - Loggen Sie Key-Nutzung für Auditing - Verwenden Sie header-basierte Auth statt Query-Parameter (sicherer)

Vermeiden: - Keys über mehrere Services hinweg teilen - Keys in Client-seitigem Code speichern (Mobile Apps, JavaScript) - Vorhersagbare Key-Muster verwenden - Keys in Anwendungslogs loggen

Key-Generierungs-Beispiel:

# Generiere sicheren Zufalls-Key
openssl rand -hex 32
# Ausgabe: 64-Zeichen Hexadezimal-String

JWT Authentication

JSON Web Tokens (JWT) bieten zustandslose, claims-basierte Authentication.

Konfiguration

authentication:
  enabled: true
  type: jwt
  jwt:
    issuer: "https://auth.example.com"
    audience: "api.example.com"
    jwks_uri: "https://auth.example.com/.well-known/jwks.json"
    algorithms:
      - RS256
      - ES256
    required_claims:
      - sub
      - email
  fail_status: 401
  fail_message: "Invalid or missing JWT token"

Parameter

  • issuer (string): Erwarteter JWT-Aussteller (iss Claim)
  • audience (string): Erwartete JWT-Audience (aud Claim)
  • jwks_uri (string): JSON Web Key Set Endpoint-URL
  • algorithms (list): Erlaubte Signatur-Algorithmen (Standard: ["RS256"])
  • required_claims (list): Claims, die im Token vorhanden sein müssen

Gängige JWT-Algorithmen

Algorithmus Typ Anwendungsfall
RS256 RSA Am häufigsten, Public Key Verification
ES256 ECDSA Kleinere Signaturen, moderne Wahl
HS256 HMAC Symmetrisch, nur für interne Services

JWKS (JSON Web Key Set)

GAL holt und cached automatisch Public Keys vom JWKS-Endpoint.

Beispiel JWKS-Endpoint:

https://auth.example.com/.well-known/jwks.json

JWKS-Struktur:

{
  "keys": [
    {
      "kty": "RSA",
      "use": "sig",
      "kid": "key-1",
      "n": "...",
      "e": "AQAB"
    }
  ]
}

JWT Claims

Standard-Claims: - iss (issuer): Token-Aussteller-URL - sub (subject): Benutzer-ID oder Identifikator - aud (audience): Vorgesehener Empfänger - exp (expiration): Token-Ablaufzeit - iat (issued at): Token-Erstellungszeit - nbf (not before): Token nicht gültig vor dieser Zeit

Custom Claims: Sie können Custom Claims hinzufügen (z.B. email, roles, permissions) und diese in Ihrem Backend validieren.

JWT Beispiel

JWT Header:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-1"
}

JWT Payload:

{
  "iss": "https://auth.example.com",
  "sub": "user123",
  "aud": "api.example.com",
  "exp": 1735689600,
  "iat": 1735686000,
  "email": "user@example.com",
  "roles": ["user", "admin"]
}

Konfigurationsoptionen

Gemeinsame Optionen

Alle Authentication-Typen teilen diese gemeinsamen Optionen:

authentication:
  enabled: true              # Authentication aktivieren/deaktivieren
  type: "api_key"           # Authentication-Typ: "basic", "api_key", "jwt"
  fail_status: 401           # HTTP-Status bei Auth-Fehlern (Standard: 401)
  fail_message: "Unauthorized"  # Fehlermeldung bei Fehlern

Typ-spezifische Optionen

Basic Auth

basic_auth:
  users:                    # Username-Passwort-Mapping
    username: "password"
  realm: "Protected"        # Authentication-Realm

API Key

api_key:
  keys:                     # Liste gültiger API Keys
    - "key1"
    - "key2"
  key_name: "X-API-Key"     # Header- oder Query-Param-Name
  in_location: "header"     # "header" oder "query"

JWT

jwt:
  issuer: "https://auth.example.com"        # Token-Aussteller
  audience: "api.example.com"               # Token-Audience
  jwks_uri: "https://auth.example.com/..."  # JWKS-Endpoint
  algorithms:                               # Erlaubte Algorithmen
    - RS256
  required_claims:                          # Erforderliche JWT-Claims
    - sub

Mehrere Routes mit unterschiedlicher Auth

services:
  - name: multi_auth_service
    type: rest
    protocol: http
    upstream:
      host: service.local
      port: 8080
    routes:
      # Öffentlicher Endpoint - keine Auth
      - path_prefix: /api/public
        methods: [GET]

      # API Key geschützt
      - path_prefix: /api/protected
        methods: [GET, POST]
        authentication:
          type: api_key
          api_key:
            keys: ["key123"]

      # Admin - Basic Auth
      - path_prefix: /api/admin
        methods: [GET, POST, DELETE]
        authentication:
          type: basic
          basic_auth:
            users:
              admin: "secret"

Provider-spezifische Implementierungen

Kong

Kong implementiert Authentication mit nativen Plugins.

Basic Auth: - Plugin: basic-auth - Features: Consumer-basierte Authentication, Credential-Speicherung

API Key: - Plugin: key-auth - Features: Flexible Key-Location (Header/Query), Consumer-Zuordnung

JWT: - Plugin: jwt - Features: JWKS-Support, Claim-Verifizierung, RS256/ES256/HS256

Generiertes Config-Beispiel:

services:
  - name: test_service
    routes:
      - name: test_service_route
        plugins:
          - name: key-auth
            config:
              key_names: [X-API-Key]
              key_in_header: true
              hide_credentials: true

APISIX

APISIX implementiert Authentication mit Plugins und JSON-Konfiguration.

Basic Auth: - Plugin: basic-auth - Features: Consumer-basiert, flexible Konfiguration

API Key: - Plugin: key-auth - Features: Header- und Query-Parameter-Support

JWT: - Plugin: jwt-auth - Features: Algorithmus-Auswahl, Issuer/Audience-Validierung

Generiertes Config-Beispiel:

{
  "routes": [
    {
      "uri": "/api/*",
      "plugins": {
        "key-auth": {
          "header": "X-API-Key"
        }
      }
    }
  ]
}

Traefik

Traefik implementiert Authentication mit Middleware.

Basic Auth: - Middleware: basicAuth - Features: Benutzerliste, Realm-Konfiguration - Hinweis: Verwenden Sie htpasswd-Format für Production

API Key: - Middleware: forwardAuth - Features: Externer Validierungsservice - Hinweis: Benötigt externen API-Key-Validator

JWT: - Middleware: forwardAuth - Features: Externer JWT-Validierungsservice - Hinweis: Benötigt externen JWT-Validator

Generiertes Config-Beispiel:

http:
  middlewares:
    test_service_router_0_auth:
      basicAuth:
        users:
          - 'admin:$apr1$...'
        realm: 'Admin Area'

Envoy

Envoy implementiert Authentication mit HTTP-Filtern.

Basic Auth: - Filter: envoy.filters.http.lua - Features: Inline Lua-Validierung - Hinweis: Production benötigt externen Auth-Service

API Key: - Filter: envoy.filters.http.lua - Features: Header-Validierung via Lua - Hinweis: Production benötigt externe Validierung

JWT: - Filter: envoy.filters.http.jwt_authn - Features: Vollständige JWT-Validierung, JWKS-Support, natives RS256/ES256 - Hinweis: Robusteste JWT-Implementierung

Generiertes Config-Beispiel:

http_filters:
  - name: envoy.filters.http.jwt_authn
    typed_config:
      providers:
        jwt_provider:
          issuer: 'https://auth.example.com'
          audiences:
            - 'api.example.com'
          remote_jwks:
            http_uri:
              uri: 'https://auth.example.com/.well-known/jwks.json'
              cluster: jwks_cluster

Nginx

Nginx implementiert Authentication mit ngx_http-Modulen und OpenResty Lua.

Basic Auth: - Modul: ngx_http_auth_basic_module - Features: Native Basic Auth, htpasswd-Unterstützung - Hinweis: Production-ready, weit verbreitet

API Key: - Modul: ngx_http_lua_module (OpenResty) - Features: Lua-basierte Header-Validierung - Hinweis: Flexibel via Lua-Scripting

JWT: - Modul: lua-resty-jwt (OpenResty) - Features: Vollständige JWT-Validierung, RS256/ES256/HS256 - Hinweis: Benötigt OpenResty, sehr performant

Generiertes Config-Beispiel:

location /api/protected {
    auth_basic "Protected Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://backend;
}

# API Key via Lua
location /api/key {
    access_by_lua_block {
        local api_key = ngx.var.http_x_api_key
        if api_key ~= "your-secret-key-123" then
            ngx.status = 401
            ngx.say("Unauthorized")
            ngx.exit(401)
        end
    }
    proxy_pass http://backend;
}

HAProxy

HAProxy implementiert Authentication mit ACLs und HTTP Header-Checks.

Basic Auth: - Feature: HTTP Basic Authentication via ACLs - Features: Native Basic Auth, Userlist-Unterstützung - Hinweis: Production-ready

API Key: - Feature: HTTP Header ACL-Checks - Features: Header-basierte Validierung - Hinweis: Einfache ACL-Regeln

JWT: - Feature: Lua-basierte Validierung - Features: Lua-Integration für Token-Validierung - Hinweis: Benötigt externe Lua-Bibliotheken

Generiertes Config-Beispiel:

# Basic Auth
userlist admins
    user admin password $6$rounds=50000$...

frontend api_front
    bind *:80
    acl is_authenticated http_auth(admins)
    http-request deny if !is_authenticated

    # API Key Check
    acl valid_api_key hdr(X-API-Key) -m str your-secret-key-123
    http-request deny if !valid_api_key

    default_backend api_backend

Azure APIM

Azure API Management implementiert Authentication mit Policy XML.

Basic Auth: - Feature: Nicht nativ unterstützt - Workaround: validate-jwt mit Custom IDP oder ForwardAuth - Hinweis: Azure AD empfohlen statt Basic Auth

API Key (Subscription Keys): - Feature: check-header Policy - Features: Native Subscription Key Management, Product-basierte Keys, Primary/Secondary Keys - Hinweis: Production-ready, Built-in Developer Portal

JWT (Azure AD): - Feature: validate-jwt Policy - Features: OpenID Connect Discovery, Azure AD Integration, Required Claims, Audience/Issuer Validation - Hinweis: Empfohlene Methode für Production

OAuth 2.0: - Feature: validate-jwt + OAuth2 Authorization Server - Features: Vollständige OAuth 2.0 Flows, Token Introspection - Hinweis: Enterprise-ready

Generiertes Config-Beispiel (Policy XML):

<!-- Subscription Keys -->
<policies>
    <inbound>
        <base />
        <check-header name="Ocp-Apim-Subscription-Key"
                      failed-check-httpcode="401"
                      failed-check-error-message="Missing or invalid subscription key" />
    </inbound>
</policies>

<!-- Azure AD JWT -->
<policies>
    <inbound>
        <base />
        <validate-jwt header-name="Authorization"
                      failed-validation-httpcode="401"
                      failed-validation-error-message="Unauthorized">
            <openid-config url="https://login.microsoftonline.com/{tenant-id}/v2.0/.well-known/openid-configuration" />
            <audiences>
                <audience>api://my-api</audience>
            </audiences>
            <required-claims>
                <claim name="roles" match="any">
                    <value>admin</value>
                    <value>user</value>
                </claim>
            </required-claims>
        </validate-jwt>
    </inbound>
</policies>

Azure APIM-spezifische Features: - Subscription Keys: Automatische Key-Generierung, Primary/Secondary Keys für Key Rotation - Developer Portal: Self-Service Subscription Management - Products: Gruppierung von APIs mit unterschiedlichen Subscription Tiers - Azure AD Integration: Native Integration ohne Custom Code - Named Values: Sichere Storage für Secrets (Azure Key Vault Integration)

GCP API Gateway

GCP API Gateway implementiert Authentication mit OpenAPI 2.0 Security Definitions und x-google-* Extensions.

JWT Authentication: - Mechanismus: x-google-issuer, x-google-jwks_uri, x-google-audiences in securityDefinitions - Features: Google Sign-In, Firebase Auth, Custom JWT Issuer, JWKS-basierte Validierung, Audience-Verifizierung - Hinweis: Nur JWT wird nativ unterstützt, OpenAPI 2.0 (Swagger) erforderlich

API Key Authentication: - Mechanismus: OpenAPI 2.0 apiKey securityDefinition mit x-google-allow Extension - Features: Header-basierte API Keys, Query-Parameter-basierte API Keys - Hinweis: Für Production wird OAuth2/JWT empfohlen

Service Account Authentication (Backend): - Mechanismus: x-google-backend mit jwt_audience für Cloud Run/Cloud Functions - Features: Automatische Service Account Token-Generierung, Backend-zu-Backend Auth - Hinweis: Transparent für Clients, nur Backend-Authentifizierung

Generiertes Config-Beispiel (JWT):

swagger: "2.0"
info:
  title: "Secure API"
  version: "1.0.0"

# JWT Security Definition
securityDefinitions:
  google_jwt:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "https://accounts.google.com"
    x-google-jwks_uri: "https://www.googleapis.com/oauth2/v3/certs"
    x-google-audiences: "https://my-project.example.com"

# Global Security Requirement
security:
  - google_jwt: []

# Backend mit Service Account Auth
x-google-backend:
  address: "https://backend-xyz.run.app"
  jwt_audience: "https://backend-xyz.run.app"
  deadline: 30.0

paths:
  /api/users:
    get:
      summary: "Get users (JWT required)"
      operationId: "getUsers"
      responses:
        200:
          description: "Success"
        401:
          description: "Unauthorized - Invalid or missing JWT"

Generiertes Config-Beispiel (API Key):

swagger: "2.0"
info:
  title: "API Key Protected API"
  version: "1.0.0"

securityDefinitions:
  api_key:
    type: "apiKey"
    name: "X-API-Key"
    in: "header"

security:
  - api_key: []

paths:
  /api/data:
    get:
      summary: "Get data (API Key required)"
      operationId: "getData"
      responses:
        200:
          description: "Success"
        401:
          description: "Unauthorized - Invalid or missing API key"

Deployment:

# API erstellen
gcloud api-gateway apis create secure-api \
  --project=my-gcp-project

# API Config mit JWT Authentication deployen
gcloud api-gateway api-configs create secure-api-config \
  --api=secure-api \
  --openapi-spec=openapi.yaml \
  --project=my-gcp-project

# Gateway erstellen
gcloud api-gateway gateways create secure-gateway \
  --api=secure-api \
  --api-config=secure-api-config \
  --location=us-central1 \
  --project=my-gcp-project

# Gateway URL abrufen
gcloud api-gateway gateways describe secure-gateway \
  --location=us-central1 \
  --project=my-gcp-project \
  --format="value(defaultHostname)"

JWT Token Testen:

# Google Sign-In Token verwenden (für x-google-issuer: accounts.google.com)
curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  https://secure-gateway-xyz.apigateway.my-gcp-project.cloud.goog/api/users

# Custom JWT Token verwenden
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
  https://secure-gateway-xyz.apigateway.my-gcp-project.cloud.goog/api/users

GCP API Gateway-spezifische Features: - Google Sign-In: Native Integration ohne zusätzliche Konfiguration (x-google-issuer: accounts.google.com) - Firebase Authentication: Direkte Unterstützung für Firebase Auth Tokens - Custom JWT Issuer: Beliebige JWKS-kompatible Issuer (Auth0, Okta, Keycloak, etc.) - Audience Validation: Strikte Audience-Prüfung für zusätzliche Sicherheit - Service Account Auth: Automatische Backend-Authentifizierung für Cloud Run/Cloud Functions - Cloud Logging: Automatisches Logging aller Auth-Failures (401 Unauthorized) - Cloud Monitoring: Metrics für Auth Success/Failure Rates

Limitierungen: - Nur OpenAPI 2.0 (Swagger) wird unterstützt, kein OpenAPI 3.0 - OAuth2 Authorization Code Flow wird nicht direkt unterstützt (nur Implicit Flow für JWT) - Basic Auth wird nicht nativ unterstützt (Workaround: Backend-basierte Basic Auth) - API Key Authentication ist limitiert (für Production wird JWT empfohlen)

AWS API Gateway

AWS API Gateway implementiert Authentication mit OpenAPI 3.0 Security Schemes und x-amazon-apigateway Extensions.

API Keys: - Mechanismus: OpenAPI 3.0 apiKey security scheme mit x-amazon-apigateway-api-key-source - Features: Usage Plans, Rate Limiting pro API Key, Subscription Management, Primary/Secondary Keys - Hinweis: Ideal für Partner-APIs, Pay-per-Use-Modelle

Lambda Authorizer (Custom JWT): - Mechanismus: x-amazon-apigateway-authorizer mit Lambda Function für Custom Authorization Logic - Features: Custom JWT Validation, Claims-basierte Authorization, Context-Weitergabe, Caching (TTL) - Hinweis: Vollständige Kontrolle über Authorization-Logik

Cognito User Pools (OAuth2/OIDC): - Mechanismus: AWS Cognito Integration via x-amazon-apigateway-authorizer (type: cognito_user_pools) - Features: OAuth2/OIDC Standard, Multi-Factor Authentication (MFA), Social Identity Providers (Google, Facebook), Managed User Pools - Hinweis: Empfohlene Methode für User-basierte APIs

IAM Authorization: - Mechanismus: AWS Signature Version 4 (SigV4) für Service-to-Service Communication - Features: IAM Roles, IAM Policies, Cross-Account Access, Temporary Credentials (STS) - Hinweis: Ideal für Service-to-Service Authentication innerhalb AWS

Generiertes Config-Beispiel (API Keys):

{
  "openapi": "3.0.1",
  "info": {
    "title": "Secure API",
    "version": "1.0.0"
  },
  "components": {
    "securitySchemes": {
      "api_key": {
        "type": "apiKey",
        "name": "x-api-key",
        "in": "header",
        "x-amazon-apigateway-api-key-source": "HEADER"
      }
    }
  },
  "security": [
    {
      "api_key": []
    }
  ],
  "paths": {
    "/secure": {
      "get": {
        "summary": "Protected endpoint",
        "responses": {
          "200": {
            "description": "Success"
          },
          "401": {
            "description": "Unauthorized - Missing or invalid API key"
          }
        },
        "x-amazon-apigateway-integration": {
          "type": "http_proxy",
          "httpMethod": "GET",
          "uri": "https://backend.example.com/secure"
        }
      }
    }
  }
}

Generiertes Config-Beispiel (Lambda Authorizer - JWT):

{
  "openapi": "3.0.1",
  "info": {
    "title": "JWT Protected API",
    "version": "1.0.0"
  },
  "components": {
    "securitySchemes": {
      "lambda_authorizer": {
        "type": "apiKey",
        "name": "Authorization",
        "in": "header",
        "x-amazon-apigateway-authtype": "custom",
        "x-amazon-apigateway-authorizer": {
          "type": "token",
          "authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:my-authorizer/invocations",
          "authorizerCredentials": "arn:aws:iam::123456789012:role/api-gateway-invoke-lambda",
          "authorizerResultTtlInSeconds": 300,
          "identitySource": "method.request.header.Authorization"
        }
      }
    }
  },
  "security": [
    {
      "lambda_authorizer": []
    }
  ]
}

Generiertes Config-Beispiel (Cognito User Pools):

{
  "openapi": "3.0.1",
  "info": {
    "title": "Cognito Protected API",
    "version": "1.0.0"
  },
  "components": {
    "securitySchemes": {
      "cognito_authorizer": {
        "type": "apiKey",
        "name": "Authorization",
        "in": "header",
        "x-amazon-apigateway-authtype": "cognito_user_pools",
        "x-amazon-apigateway-authorizer": {
          "type": "cognito_user_pools",
          "providerARNs": [
            "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_AbCdEfGhI"
          ]
        }
      }
    }
  },
  "security": [
    {
      "cognito_authorizer": []
    }
  ]
}

Deployment:

# OpenAPI generieren
gal generate -c config.yaml -p aws_apigateway -o api.json

# API erstellen
API_ID=$(aws apigateway import-rest-api \
  --body file://api.json \
  --query 'id' --output text)

# API Key erstellen (für API Key Authentication)
aws apigateway create-api-key \
  --name "MyAppKey" \
  --enabled

# Usage Plan erstellen (Rate Limiting)
aws apigateway create-usage-plan \
  --name "BasicPlan" \
  --throttle burstLimit=1000,rateLimit=500 \
  --api-stages apiId=$API_ID,stage=prod

# Deployment erstellen
aws apigateway create-deployment \
  --rest-api-id $API_ID \
  --stage-name prod

# API URL anzeigen
echo "https://${API_ID}.execute-api.us-east-1.amazonaws.com/prod"

API Key Testen:

# API Key Request
curl -H "x-api-key: your-api-key-here" \
  https://${API_ID}.execute-api.us-east-1.amazonaws.com/prod/secure

Lambda Authorizer Testen:

# JWT Token Request (Lambda validiert das Token)
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
  https://${API_ID}.execute-api.us-east-1.amazonaws.com/prod/protected

Cognito Token Testen:

# Cognito User Login
aws cognito-idp initiate-auth \
  --auth-flow USER_PASSWORD_AUTH \
  --client-id <client-id> \
  --auth-parameters USERNAME=user@example.com,PASSWORD=SecurePass123

# Cognito ID Token verwenden
curl -H "Authorization: Bearer <id-token>" \
  https://${API_ID}.execute-api.us-east-1.amazonaws.com/prod/profile

AWS API Gateway-spezifische Features: - Usage Plans: API Key-basierte Subscription-Modelle mit Rate Limiting & Quotas - Lambda Authorizer: Vollständige Kontrolle über Authorization-Logik (JWT, OAuth2, Custom) - Cognito Integration: Managed User Pools, OAuth2/OIDC, MFA, Social Logins - IAM Authorization: Service-to-Service Auth mit AWS Signature v4 - API Key Rotation: Primary/Secondary Keys für Zero-Downtime Key-Rotation - CloudWatch Logs: Automatisches Logging aller Auth-Failures (401 Unauthorized) - CloudWatch Metrics: Auth Success/Failure Rates, Latency-Metriken - X-Ray Tracing: Distributed Tracing für Authorization-Flow

Limitierungen: - ⚠️ Lambda Authorizer: Cold Start bei erstem Request (Warmup empfohlen) - ⚠️ Lambda Authorizer: 29 Sekunden Timeout-Limit (API Gateway Maximum) - ⚠️ API Gateway Timeout: Max 29 Sekunden für gesamten Request (inkl. Authorization) - ⚠️ Cognito: AWS Lock-in, Kosten pro Monthly Active User (MAU) - ❌ Basic Auth: Nicht nativ unterstützt (Workaround: Lambda Authorizer)

Best Practices

Allgemeine Sicherheit

  1. Verwenden Sie immer HTTPS in Production
  2. Schützt Credentials und Tokens während der Übertragung
  3. Erforderlich für Basic Auth und API Keys
  4. Empfohlen für alle Authentication-Typen

  5. Verwenden Sie starke Credentials

  6. Passwörter: Mindestens 12 Zeichen, gemischte Groß-/Kleinschreibung, Sonderzeichen
  7. API Keys: Mindestens 32 Zeichen, kryptographisch zufällig
  8. JWT-Secrets: Mindestens 256 Bits für HS256

  9. Rotieren Sie Credentials regelmäßig

  10. API Keys: Alle 90 Tage
  11. JWT-Signatur-Keys: Alle 6-12 Monate
  12. Passwörter: Alle 90 Tage oder bei Kompromittierung

  13. Implementieren Sie Rate Limiting

  14. Kombinieren Sie Authentication mit Rate Limiting
  15. Schutz vor Brute-Force-Angriffen
  16. Verwenden Sie per-User- oder per-Key-Limits

Authentication-Typ-Auswahl

Verwenden Sie Basic Auth wenn: - Interne Tools und Admin-Interfaces - Kleine Anzahl bekannter Benutzer - Einfachheit wichtiger als erweiterte Features

Verwenden Sie API Key wenn: - Service-to-Service-Kommunikation - Externer API-Zugriff für Partner - Einfaches Credential-Management benötigt

Verwenden Sie JWT wenn: - Moderne Web- oder Mobile-Anwendungen - Microservices-Architektur - Zustandslose Authentication erforderlich - Kurzlebige Tokens benötigt - Claims-basierte Authorization erforderlich

Production-Überlegungen

  1. Niemals Credentials hardcoden

    # Schlecht - hardcoded in Config
    users:
      admin: "password123"
    
    # Gut - Umgebungsvariablen verwenden
    users:
      admin: "${ADMIN_PASSWORD}"
    

  2. Verwenden Sie Secrets Management

  3. HashiCorp Vault
  4. AWS Secrets Manager
  5. Kubernetes Secrets
  6. Azure Key Vault

  7. Implementieren Sie korrektes Logging

  8. Loggen Sie Authentication-Versuche (Erfolg und Fehler)
  9. Loggen Sie keine Credentials oder Tokens
  10. Überwachen Sie verdächtige Muster

  11. Fügen Sie Monitoring und Alerting hinzu

  12. Tracken Sie Authentication-Fehlerquoten
  13. Alarmieren bei ungewöhnlichen Mustern
  14. Überwachen Sie Token-Ablauf und Rotation

Testing

Testing Basic Auth

# Gültige Credentials
curl -u admin:secret http://localhost:10000/api/admin
# Erwartet: 200 OK

# Ungültige Credentials
curl -u admin:wrong http://localhost:10000/api/admin
# Erwartet: 401 Unauthorized

# Fehlende Credentials
curl http://localhost:10000/api/admin
# Erwartet: 401 Unauthorized

Testing API Key Auth

# Gültiger API Key im Header
curl -H "X-API-Key: key_123abc" http://localhost:10000/api/protected
# Erwartet: 200 OK

# Gültiger API Key im Query-Parameter
curl "http://localhost:10000/api/protected?api_key=key_123abc"
# Erwartet: 200 OK

# Ungültiger API Key
curl -H "X-API-Key: invalid_key" http://localhost:10000/api/protected
# Erwartet: 401 Unauthorized

# Fehlender API Key
curl http://localhost:10000/api/protected
# Erwartet: 401 Unauthorized

Testing JWT Auth

Generieren Sie zuerst einen Test-JWT-Token auf https://jwt.io oder mit einer Bibliothek:

import jwt
import time

# Generiere JWT
payload = {
    "iss": "https://auth.example.com",
    "sub": "user123",
    "aud": "api.example.com",
    "exp": int(time.time()) + 3600,
    "iat": int(time.time())
}

# Verwenden Sie Ihren Private Key
token = jwt.encode(payload, private_key, algorithm="RS256")
# Gültiger JWT Token
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" http://localhost:10000/api/user
# Erwartet: 200 OK

# Ungültiger JWT Token
curl -H "Authorization: Bearer invalid.token.here" http://localhost:10000/api/user
# Erwartet: 401 Unauthorized

# Fehlender Authorization-Header
curl http://localhost:10000/api/user
# Erwartet: 401 Unauthorized

# Abgelaufener Token
curl -H "Authorization: Bearer EXPIRED_TOKEN" http://localhost:10000/api/user
# Erwartet: 401 Unauthorized

Load Testing mit Authentication

# Apache Bench mit API Key
ab -n 1000 -c 10 -H "X-API-Key: key_123abc" http://localhost:10000/api/protected

# wrk mit JWT
wrk -t4 -c100 -d30s -H "Authorization: Bearer YOUR_JWT" http://localhost:10000/api/user

Troubleshooting

Häufige Probleme

1. 401 Unauthorized trotz korrekter Credentials

Symptom: Authentication schlägt fehl trotz korrekter Credentials

Mögliche Ursachen: - Credentials nicht korrekt im Gateway konfiguriert - Tippfehler in Username/Passwort/Key - Falscher Authentication-Typ konfiguriert - Groß-/Kleinschreibungsprobleme

Lösung:

# Prüfe generierte Config
python gal-cli.py generate -f examples/authentication-test.yaml

# Verifiziere Credentials in Ausgabe
# Für Basic Auth, prüfe users-Sektion
# Für API Key, prüfe keys-Liste
# Für JWT, verifiziere issuer/audience

2. JWT-Validierung schlägt fehl

Symptom: Gültige JWT-Tokens werden abgelehnt

Mögliche Ursachen: - Falscher Issuer oder Audience - JWKS-Endpoint nicht erreichbar - Token abgelaufen - Algorithmus-Mismatch - Erforderliche Claims fehlen

Lösung:

# Verifiziere JWT auf jwt.io
# Prüfe ob Issuer mit Konfiguration übereinstimmt
# Verifiziere JWKS-Endpoint ist erreichbar
curl https://auth.example.com/.well-known/jwks.json

# Prüfe Token-Ablauf
# Verifiziere Algorithmus im JWT-Header stimmt mit Config überein

3. API Key wird nicht erkannt

Symptom: API Key im Header/Query wird nicht validiert

Mögliche Ursachen: - Key-Name-Mismatch (case-sensitive) - Location-Mismatch (header vs query) - Key nicht in konfigurierter Keys-Liste - Sonderzeichen im Key verursachen Parsing-Probleme

Lösung:

# Verifiziere Konfiguration
authentication:
  type: api_key
  api_key:
    key_name: X-API-Key  # Muss exakt übereinstimmen (case-sensitive)
    in_location: header   # Muss mit Request-Location übereinstimmen
    keys:
      - "your_actual_key"  # Muss exakt übereinstimmen

4. Basic Auth Prompts erscheinen nicht

Symptom: Browser zeigt keinen Authentication-Prompt

Mögliche Ursachen: - Falsche Realm-Konfiguration - Vorher gecachte Credentials - Browser-Sicherheitseinstellungen

Lösung: - Browser-Cache und Cookies löschen - Zuerst mit curl testen - Verifizieren, dass Realm korrekt konfiguriert ist

5. JWKS Fetch-Fehler (Envoy)

Symptom: Envoy kann JWKS nicht abrufen

Mögliche Ursachen: - JWKS-Cluster nicht konfiguriert - DNS-Auflösungsfehler - HTTPS-Zertifikat-Validierungsfehler - Netzwerkverbindungsprobleme

Lösung: - Verifizieren Sie, dass JWKS-URL erreichbar ist - Prüfen Sie, dass Cluster-Konfiguration TLS-Einstellungen enthält - Testen Sie JWKS-Endpoint manuell:

curl https://auth.example.com/.well-known/jwks.json

Debug-Modus

Aktivieren Sie Debug-Logging für Troubleshooting:

# Generiere Config mit ausführlicher Ausgabe
python gal-cli.py generate -f config.yaml --verbose

# Prüfe Gateway-Logs
# Kong
docker logs <kong-container>

# APISIX
docker logs <apisix-container>

# Traefik
docker logs <traefik-container>

# Envoy
docker logs <envoy-container>

Migrationsleitfaden

Von v1.0.0 zu v1.1.0

Authentication ist ein neues Feature in v1.1.0. Bestehende Konfigurationen ohne Authentication funktionieren weiterhin.

Authentication zu bestehenden Routes hinzufügen:

# Vorher (v1.0.0)
routes:
  - path_prefix: /api/users
    methods: [GET, POST]

# Nachher (v1.1.0)
routes:
  - path_prefix: /api/users
    methods: [GET, POST]
    authentication:  # Neues Feld
      enabled: true
      type: api_key
      api_key:
        keys: ["your_key"]

Kombination mit Rate Limiting

Authentication und Rate Limiting funktionieren nahtlos zusammen:

routes:
  - path_prefix: /api/premium
    authentication:
      type: jwt
      jwt:
        issuer: "https://auth.example.com"
    rate_limit:
      enabled: true
      requests_per_second: 1000
      key_type: jwt_claim
      key_claim: sub  # Rate Limit pro JWT-Subject

Erweiterte Themen

Multi-Tenancy mit JWT Claims

Verwenden Sie JWT Claims für Multi-Tenant Rate Limiting:

rate_limit:
  enabled: true
  key_type: jwt_claim
  key_claim: tenant_id  # Custom Claim
  requests_per_second: 100

OAuth 2.0 Integration

GAL JWT-Support funktioniert mit jedem OAuth 2.0 / OIDC-Provider:

  • Auth0
  • Okta
  • Keycloak
  • AWS Cognito
  • Azure AD
  • Google Cloud Identity

Konfigurieren Sie den JWKS-Endpoint von Ihrem OAuth-Provider:

jwt:
  issuer: "https://your-tenant.auth0.com/"
  audience: "https://your-api.example.com"
  jwks_uri: "https://your-tenant.auth0.com/.well-known/jwks.json"

Custom Authentication

Für Custom-Authentication-Anforderungen, die nicht von eingebauten Typen abgedeckt werden:

  1. Traefik: Verwenden Sie forwardAuth Middleware mit Custom-Validierungsservice
  2. Envoy: Verwenden Sie ext_authz Filter mit Custom gRPC/HTTP-Service
  3. Kong: Entwickeln Sie Custom Plugin
  4. APISIX: Verwenden Sie Serverless Plugin mit Lua-Code

Zusammenfassung

GAL v1.1.0 bietet umfassende Authentication-Unterstützung:

✅ Drei Authentication-Typen: Basic, API Key, JWT ✅ Alle sechs Gateway-Provider unterstützt (Envoy, Kong, APISIX, Traefik, Nginx, HAProxy) ✅ Per-Route Authentication-Konfiguration ✅ Kombination mit Rate Limiting ✅ Production-ready JWT mit JWKS-Support ✅ Flexibles Credential-Management

Für Fragen oder Probleme, besuchen Sie: https://github.com/pt9912/x-gal/issues