---
title: "Add JWT Authentication to Your Slim API"
description: "Secure your Slim API using JWT authentication with JWKS."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/php/slim/jwt-backend"
framework: "Slim"
language: "PHP"
authStrategy: "JWT with JWKS"
pageType: use-case
---

# Add JWT Authentication to Your Slim API

Secure your Slim API using JWT authentication with JWKS.

## How Zuplo Handles It

Let Zuplo issue short-lived JWTs signed with a JWKS your Slim backend can verify — no long-lived API keys touch your origin.

## Slim Backend Code

```php
<?php

require 'vendor/autoload.php';

use Slim\Factory\AppFactory;
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
use GuzzleHttp\Client;

$app = AppFactory::create();

// Constants
const ISSUER = "https://my-api-a32f34.zuplo.api/__zuplo/issuer";
const JWKS_URI = ISSUER . "/.well-known/jwks.json";

// Middleware to validate JWT
$jwtMiddleware = function ($request, $handler) {
    $authHeader = $request->getHeader('Authorization');
    if (!$authHeader) {
        return $handler->handle($request)->withStatus(401)->withJson(['error' => 'No token provided']);
    }

    $token = str_replace('Bearer ', '', $authHeader[0]);

    try {
        // Fetch JWKS and verify token
        $client = new Client();
        $response = $client->get(JWKS_URI);
        $jwks = json_decode($response->getBody(), true);

        $decoded = JWT::decode($token, JWK::parseKeySet($jwks), ['RS256']);
        $request = $request->withAttribute('user', $decoded);
    } catch (Exception $e) {
        return $handler->handle($request)->withStatus(401)->withJson(['error' => 'Invalid token', 'details' => $e->getMessage()]);
    }

    return $handler->handle($request);
};

// Example protected route
$app->get('/protected', function ($request, $response, $args) {
    $user = $request->getAttribute('user');
    $response->getBody()->write(json_encode([
        'message' => 'Access granted',
        'user' => $user
    ]));
    return $response->withHeader('Content-Type', 'application/json');
})->add($jwtMiddleware);

$app->run();
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
