# Eine API schützen

Die Access Token der Plattform in Ihrer eigenen API validieren, mit Beispielen für Node.js, Python, Java, C#, Go, PHP und Rust.

Die anderen Quickstarts behandeln die Client-Seite: eine Anwendung, die Token bezieht. Diese Anleitung behandelt die **Resource-Server**-Seite: Ihre eigene API, die die von der Plattform ausgestellten Access Token validiert, bevor sie eine Anfrage bedient. Die Beispiele decken Node.js, Python, Java, C#, Go, PHP und Rust ab; die Prüfungen sind in jeder Sprache und jedem Framework dieselben.

Access Token, die für eine registrierte API ausgestellt werden, sind **signierte JWTs**. Ihre API validiert sie offline gegen die veröffentlichten Signaturschlüssel der Plattform; pro Anfrage ist kein Aufruf der Plattform nötig.

## 1. Die API registrieren

Registrieren Sie Ihre API in der Admin Console unter **Integrations → APIs** mit einer **Kennung** (zum Beispiel `https://api.example.com`), definieren Sie ihre **Scopes** und autorisieren Sie mindestens eine Anwendung für den Aufruf. Die vollständige Anleitung finden Sie unter [APIs](https://dts-identity.com/de/docs/integrations/apis.md). Clients fordern Token *für Ihre API* an, indem sie deren Kennung als Resource Indicator übergeben; der `aud`-Claim des Tokens trägt sie.

## 2. Abhängigkeiten installieren

```bash tab="Node.js" tab-group="lang"
npm install express jose
```

```bash tab="Python" tab-group="lang"
pip install fastapi uvicorn "pyjwt[crypto]"
```

```groovy tab="Java" tab-group="lang"
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
```

```bash tab="C#" tab-group="lang"
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
```

```bash tab="Go" tab-group="lang"
go get github.com/golang-jwt/jwt/v5 github.com/MicahParks/keyfunc/v3
```

```bash tab="PHP" tab-group="lang"
composer require firebase/php-jwt
```

```bash tab="Rust" tab-group="lang"
cargo add axum jsonwebtoken serde_json
cargo add tokio --features full
cargo add reqwest --features json
```

## 3. Den Token validieren

Prüfen Sie bei jeder Anfrage vier Dinge, in dieser Reihenfolge: die **Signatur** (gegen das JWKS der Plattform), den **Issuer**, die **Audience** (die Kennung Ihrer API) und den **Ablauf**. Jede Bibliothek erledigt alle vier in einem Aufruf:

```js tab="Node.js" tab-group="lang"
import express from 'express';
import { createRemoteJWKSet, jwtVerify } from 'jose';

const ISSUER = 'https://<your-domain>';           // your instance's login domain
const AUDIENCE = 'https://api.example.com';       // your API's identifier

// Fetches and caches the platform's signing keys, and refreshes them on rotation.
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks`));

async function requireAccessToken(req, res, next) {
  const auth = req.headers.authorization ?? '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;
  if (!token) {
    return res.status(401).set('WWW-Authenticate', 'Bearer').end();
  }
  try {
    const { payload } = await jwtVerify(token, jwks, {
      issuer: ISSUER,
      audience: AUDIENCE,
    });
    req.claims = payload; // sub, scope, client_id, ...
    return next();
  } catch {
    return res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').end();
  }
}
```

```python tab="Python" tab-group="lang"
import jwt
from fastapi import HTTPException, Request
from jwt import PyJWKClient

ISSUER = "https://<your-domain>"          # your instance's login domain
AUDIENCE = "https://api.example.com"      # your API's identifier

# Fetches and caches the platform's signing keys.
jwks = PyJWKClient(f"{ISSUER}/.well-known/jwks")

def require_access_token(request: Request) -> dict:
    auth = request.headers.get("authorization", "")
    if not auth.startswith("Bearer "):
        raise HTTPException(401, headers={"WWW-Authenticate": "Bearer"})
    token = auth[7:]
    try:
        key = jwks.get_signing_key_from_jwt(token).key
        return jwt.decode(  # sub, scope, client_id, ...
            token, key,
            algorithms=["RS256"],  # the signing algorithm configured on your API
            issuer=ISSUER,
            audience=AUDIENCE,
        )
    except jwt.InvalidTokenError:
        raise HTTPException(401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'})
```

```yaml tab="Java" tab-group="lang"
# application.yml. Spring Boot reads the discovery document and validates
# signature, issuer, audience, and expiry against the platform's JWKS.
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://<your-domain>     # your instance's login domain
          audiences: https://api.example.com    # your API's identifier
```

```csharp tab="C#" tab-group="lang"
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

const string Issuer = "https://<your-domain>";      // your instance's login domain
const string Audience = "https://api.example.com";  // your API's identifier

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // Reads the discovery document, then fetches and caches the signing keys.
        options.Authority = Issuer;
        options.Audience = Audience;
        options.MapInboundClaims = false; // keep the raw claim names (sub, scope, ...)
    });
```

```go tab="Go" tab-group="lang"
import (
	"net/http"
	"strings"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

const issuer = "https://<your-domain>"      // your instance's login domain
const audience = "https://api.example.com"  // your API's identifier

// Fetches and caches the platform's signing keys.
var jwks, _ = keyfunc.NewDefault([]string{issuer + "/.well-known/jwks"})

func requireAccessToken(w http.ResponseWriter, r *http.Request) (jwt.MapClaims, bool) {
	auth := r.Header.Get("Authorization")
	if !strings.HasPrefix(auth, "Bearer ") {
		w.Header().Set("WWW-Authenticate", "Bearer")
		w.WriteHeader(http.StatusUnauthorized)
		return nil, false
	}
	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(strings.TrimPrefix(auth, "Bearer "), claims, jwks.Keyfunc,
		jwt.WithValidMethods([]string{"RS256"}), // the signing algorithm configured on your API
		jwt.WithIssuer(issuer),
		jwt.WithAudience(audience),
		jwt.WithExpirationRequired(),
	)
	if err != nil {
		w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
		w.WriteHeader(http.StatusUnauthorized)
		return nil, false
	}
	return claims, true // sub, scope, client_id, ...
}
```

```php tab="PHP" tab-group="lang"
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;

const ISSUER = 'https://<your-domain>';        // your instance's login domain
const AUDIENCE = 'https://api.example.com';    // your API's identifier

function requireAccessToken(): array {
    $auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (!str_starts_with($auth, 'Bearer ')) {
        header('WWW-Authenticate: Bearer');
        http_response_code(401);
        exit;
    }
    try {
        // Cache the JWKS between requests (APCu, Redis, ...) instead of re-fetching.
        $jwks = json_decode(file_get_contents(ISSUER . '/.well-known/jwks'), true);
        $claims = (array) JWT::decode(substr($auth, 7), JWK::parseKeySet($jwks, 'RS256'));
        if (($claims['iss'] ?? '') !== ISSUER || ($claims['aud'] ?? '') !== AUDIENCE) {
            throw new UnexpectedValueException('wrong issuer or audience');
        }
        return $claims; // sub, scope, client_id, ...
    } catch (Exception $e) {
        header('WWW-Authenticate: Bearer error="invalid_token"');
        http_response_code(401);
        exit;
    }
}
```

```rust tab="Rust" tab-group="lang"
use axum::http::{HeaderMap, StatusCode};
use jsonwebtoken::{decode, decode_header, jwk::JwkSet, Algorithm, DecodingKey, Validation};
use serde_json::Value;

const ISSUER: &str = "https://<your-domain>";      // your instance's login domain
const AUDIENCE: &str = "https://api.example.com";  // your API's identifier

// Fetch once at startup and cache; refresh when a kid is unknown.
async fn fetch_jwks() -> JwkSet {
    reqwest::get(format!("{ISSUER}/.well-known/jwks")).await.unwrap().json().await.unwrap()
}

fn require_access_token(jwks: &JwkSet, headers: &HeaderMap) -> Result<Value, StatusCode> {
    let token = headers.get("authorization")
        .and_then(|h| h.to_str().ok())
        .and_then(|h| h.strip_prefix("Bearer "))
        .ok_or(StatusCode::UNAUTHORIZED)?;

    let kid = decode_header(token).map_err(|_| StatusCode::UNAUTHORIZED)?.kid;
    let jwk = kid.as_deref().and_then(|k| jwks.find(k)).ok_or(StatusCode::UNAUTHORIZED)?;

    // RS256: the signing algorithm configured on your API
    let mut validation = Validation::new(Algorithm::RS256);
    validation.set_issuer(&[ISSUER]);
    validation.set_audience(&[AUDIENCE]);

    let data = decode::<Value>(token, &DecodingKey::from_jwk(jwk).unwrap(), &validation)
        .map_err(|_| StatusCode::UNAUTHORIZED)?;
    Ok(data.claims) // sub, scope, client_id, ...
}
```

Überspringen Sie nie die Audience-Prüfung: Ein Token, der für eine andere API geprägt wurde, oder ein ID Token (dessen Audience die Client ID der Anwendung ist) muss hier abgelehnt werden. Siehe [Die API als verifizierbarer Vertrag](https://dts-identity.com/de/docs/integrations/apis.md#the-api-as-a-verifiable-contract).

## 4. Scopes durchsetzen

Der `scope`-Claim des Tokens ist eine durch Leerzeichen getrennte Zeichenkette der Scopes, die dem Aufrufer tatsächlich gewährt wurden. Ein fehlender Token ist ein **401**; ein gültiger Token ohne den erforderlichen Scope ist ein **403**:

```js tab="Node.js" tab-group="lang"
function needScope(scope) {
  return (req, res, next) => {
    const granted = (req.claims.scope ?? '').split(' ');
    if (!granted.includes(scope)) {
      return res.status(403).json({ error: 'insufficient_scope', required: scope });
    }
    return next();
  };
}

const app = express();

app.get('/orders', requireAccessToken, needScope('orders.read'), (req, res) => {
  res.json({ orders: [], caller: req.claims.sub });
});

app.listen(8080);
```

```python tab="Python" tab-group="lang"
from fastapi import Depends, FastAPI

def need_scope(scope: str):
    def check(claims: dict = Depends(require_access_token)) -> dict:
        granted = (claims.get("scope") or "").split(" ")
        if scope not in granted:
            raise HTTPException(403, {"error": "insufficient_scope", "required": scope})
        return claims
    return check

app = FastAPI()

@app.get("/orders")
def orders(claims: dict = Depends(need_scope("orders.read"))):
    return {"orders": [], "caller": claims["sub"]}

# run with: uvicorn main:app --port 8080
```

```java tab="Java" tab-group="lang"
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http.oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()))
        .authorizeHttpRequests(auth -> auth
            // Spring maps the scope claim to SCOPE_* authorities automatically.
            .requestMatchers("/orders").hasAuthority("SCOPE_orders.read")
            .anyRequest().authenticated());
    return http.build();
}

@RestController
class OrdersController {
    @GetMapping("/orders")
    Map<String, Object> orders(@AuthenticationPrincipal Jwt jwt) {
        return Map.of("orders", List.of(), "caller", jwt.getSubject());
    }
}
```

```csharp tab="C#" tab-group="lang"
using System.Security.Claims;

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("orders.read", policy => policy.RequireAssertion(ctx =>
        (ctx.User.FindFirst("scope")?.Value ?? "").Split(' ').Contains("orders.read")));
});

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/orders", (ClaimsPrincipal user) =>
    Results.Json(new { orders = Array.Empty<object>(), caller = user.FindFirst("sub")?.Value }))
    .RequireAuthorization("orders.read");

app.Run("http://localhost:8080");
```

```go tab="Go" tab-group="lang"
import (
	"encoding/json"
	"slices"
)

func needScope(w http.ResponseWriter, claims jwt.MapClaims, scope string) bool {
	granted, _ := claims["scope"].(string)
	if !slices.Contains(strings.Split(granted, " "), scope) {
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(map[string]string{"error": "insufficient_scope", "required": scope})
		return false
	}
	return true
}

func main() {
	http.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
		claims, ok := requireAccessToken(w, r)
		if !ok || !needScope(w, claims, "orders.read") {
			return
		}
		json.NewEncoder(w).Encode(map[string]any{"orders": []any{}, "caller": claims["sub"]})
	})
	http.ListenAndServe(":8080", nil)
}
```

```php tab="PHP" tab-group="lang"
function needScope(array $claims, string $scope): void {
    $granted = explode(' ', $claims['scope'] ?? '');
    if (!in_array($scope, $granted, true)) {
        http_response_code(403);
        header('Content-Type: application/json');
        exit(json_encode(['error' => 'insufficient_scope', 'required' => $scope]));
    }
}

// e.g. in orders.php
$claims = requireAccessToken();
needScope($claims, 'orders.read');

header('Content-Type: application/json');
echo json_encode(['orders' => [], 'caller' => $claims['sub']]);
```

```rust tab="Rust" tab-group="lang"
use axum::{extract::State, routing::get, Json, Router};
use serde_json::json;

fn need_scope(claims: &Value, scope: &str) -> Result<(), StatusCode> {
    let granted = claims["scope"].as_str().unwrap_or("");
    if granted.split(' ').any(|s| s == scope) { Ok(()) } else { Err(StatusCode::FORBIDDEN) }
}

async fn orders(State(jwks): State<&'static JwkSet>, headers: HeaderMap) -> Result<Json<Value>, StatusCode> {
    let claims = require_access_token(jwks, &headers)?;
    need_scope(&claims, "orders.read")?;
    Ok(Json(json!({ "orders": [], "caller": claims["sub"] })))
}

#[tokio::main]
async fn main() {
    let jwks: &'static JwkSet = Box::leak(Box::new(fetch_jwks().await));
    let app = Router::new().route("/orders", get(orders)).with_state(jwks);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

Der `sub`-Claim des Tokens identifiziert den Aufrufer: den Benutzer bei benutzergebundenen Token, die Anwendung bei Machine-to-Machine-Token. Ein Scope im Token ist eine Gewährung, keine Garantie; setzen Sie weiterhin eigene Prüfungen auf Objektebene durch (besitzt *dieser* Aufrufer *diesen* Datensatz?).

Hat die API [RBAC](https://dts-identity.com/de/docs/integrations/apis.md#role-based-access-control) aktiviert, tragen benutzergebundene Token zusätzlich die Berechtigungen des Benutzers in einem `permissions`-Claim (und optional `roles`), die Sie auf dieselbe Weise prüfen können.

## 5. Ausprobieren

Fordern Sie einen Token für Ihre API an und rufen Sie sie auf. Die Registerkarte **Test** der API in der Admin Console generiert diese Befehle vorbefüllt; von Hand, mit einer Machine-to-Machine-Anwendung:

```bash
TOKEN=$(curl -s -X POST https://<your-domain>/oauth/token \
  -d grant_type=client_credentials \
  -d client_id=$CLIENT_ID -d client_secret=$CLIENT_SECRET \
  -d resource=https://api.example.com \
  -d scope=orders.read | jq -r .access_token)

curl -s http://localhost:8080/orders -H "Authorization: Bearer $TOKEN"
```

Token, die im Namen eines angemeldeten Benutzers bezogen wurden (eine interaktive Anwendung, die die Kennung Ihrer API bei der Anmeldung als Resource Indicator übergibt), werden auf exakt dieselbe Weise validiert.

## Fehlerbehebung

- **Der Token ist kein JWT** (er besteht nicht aus drei durch Punkte getrennten Segmenten). Er wurde ohne die Kennung Ihrer API als Resource Indicator angefordert, sodass die Plattform einen opaken Token ausgestellt hat, der nur am UserInfo-Endpunkt gültig ist. Fordern Sie den Token *für Ihre API* an.
- **Die Audience-Prüfung schlägt fehl.** Der Token wurde für eine andere API geprägt, oder Sie vergleichen gegen den falschen Wert: Die Audience muss exakt der registrierten Kennung Ihrer API entsprechen.
- **Der Scope fehlt, obwohl der Token gültig ist.** Scopes, die dem Aufrufer nicht gewährt wurden, werden stillschweigend aus dem Token verworfen; siehe [Scopes vs. Berechtigungen](https://dts-identity.com/de/docs/integrations/apis.md#scopes-vs-permissions).
- **Die Validierung schlägt nur manchmal fehl, direkt nach der Anmeldung.** Prüfen Sie auf Zeitabweichung zwischen Ihrem Server und der Plattform; halten Sie die Uhr Ihres Servers per NTP synchron (die Bibliotheken akzeptieren auch eine kleine Zeittoleranz).

## Weiter

- [Tokens](https://dts-identity.com/de/docs/reference/tokens.md): wofür jeder Token-Typ da ist und wie lange er lebt.
- [APIs](https://dts-identity.com/de/docs/integrations/apis.md): Scopes, Zugriffsrichtlinien, Token-Lebensdauern und das Audience-Design eines Microservice-Backends.
