Search by

kraz / json-rpc-server-bundle

kraz1

Symfony bundle for kraz/json-rpc-server: JSON-RPC 2.0 endpoints with Security, RateLimiter, Serializer and Validator integration

Package info

github.com/kraz/json-rpc-server-bundle

Type:symfony-bundle

pkg:composer/kraz/json-rpc-server-bundle

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-11-26 10:53 UTC

This package is auto-updated.

Last update: 2026-11-26 11:02:41 UTC


README

CI Packagist Version GitHub license

Symfony integration of kraz/json-rpc-server: JSON-RPC 2.0 endpoints for a Symfony 8 application.

  • Any number of named servers, each one an endpoint with its own methods and settings.
  • Methods are services: a class carrying #[JsonRpcService] is picked up by autoconfiguration, lazily instantiated.
  • Security: the firewall authenticates (JWT, static API keys, sessions, ...), the server authorizes per method with the voters of the application.
  • Service Mapping Description at GET <path>?smd, listing what the caller may call.
  • RateLimiter, Serializer, Validator, Monolog and Cache are used when they are installed.
  • Mistakes in the declarations fail the build of the container, not a request.

Installation

composer require kraz/json-rpc-server-bundle
// config/bundles.php
return [
    // ...
    Kraz\JsonRpcServerBundle\KrazJsonRpcServerBundle::class => ['all' => true],
];
# config/routes/json_rpc.yaml
json_rpc:
    resource: .
    type: kraz_json_rpc_server

Configuration

# config/packages/kraz_json_rpc_server.yaml
kraz_json_rpc_server:
    object_mapping: native          # or "serializer", see "Parameters and results"
    validation: true                # validate object parameters with symfony/validator

    servers:
        default:
            path: /api/rpc          # the route "kraz_json_rpc_server.default"; leave out to define it yourself
            host: ~
            description: 'Public API'
            default_access: authenticated   # or "public": for methods without an access attribute
            smd: true               # GET /api/rpc?smd
            max_batch_size: 100     # 0: unlimited
            max_body_size: 1048576  # bytes; 0: unlimited
            rate_limiter: ~         # a limiter of framework.rate_limiter
            cache_pool: cache.system    # method metadata; unused in debug mode
            debug: ~                # exception details in "Internal error"; kernel.debug by default
        admin:
            path: /api/rpc/admin

    api_keys:                       # see "Static API keys"
        header: X-API-Key
        query_parameter: ~          # e.g. "key": also accept /api/rpc?key=<key>
        keys: {}

Without any server a default one is created at /json-rpc. bin/console debug:json-rpc [server] lists the servers and their methods.

Methods

namespace App\JsonRpc;

use Kraz\JsonRpcServer\Attribute\JsonRpcMethod;
use Kraz\JsonRpcServer\Attribute\JsonRpcService;
use Kraz\JsonRpcServer\Attribute\PublicAccess;
use Kraz\JsonRpcServer\Attribute\RequiresPermission;
use Kraz\JsonRpcServerBundle\Security\SecurityIdentity;

#[JsonRpcService('orders', description: 'Order management')]
final class OrderService
{
    public function __construct(private OrderRepository $orders)
    {
    }

    /**
     * @param int $id the number of the order
     */
    #[JsonRpcMethod]
    public function find(int $id, SecurityIdentity $identity): Order
    {
        return $this->orders->getFor($identity->getUser(), $id);
    }

    #[JsonRpcMethod]
    #[RequiresPermission('ROLE_BACKOFFICE')]
    public function cancel(int $id, ?string $reason = null): bool { /* ... */ }

    #[JsonRpcMethod]
    #[PublicAccess]
    public function statuses(): array { /* ... */ }
}

With autoconfiguration there is nothing else to do; otherwise tag the service kraz_json_rpc_server.service.

A service belongs to the default server unless it says otherwise, on the class or on a method:

#[JsonRpcService('maintenance', servers: 'admin')]
#[JsonRpcService('catalog', servers: ['default', 'partners'])]
#[JsonRpcMethod(servers: 'admin')]

See kraz/json-rpc-server for the rules of parameter binding, the injectable parameters (Context, Request, the identity), errors and middleware.

Parameters and results

A parameter which is a class is built from a JSON object. With object_mapping: native its members are passed to the constructor by name; with object_mapping: serializer the Symfony Serializer denormalizes it (serialized names, discriminators, collections, ...). Either way the object is then validated with the Symfony Validator, and the violations are answered as -32602 Invalid params:

{"code": -32602, "message": "Invalid params: \"product\" is not valid.", "data": {
    "parameter": "product",
    "violations": [{"path": "product.price", "message": "This value should be positive."}]
}}

A method may return objects: when the Serializer is installed it normalizes the result.

Exceptions

AccessDeniedException and AuthenticationException of the Security component, and ValidationFailedException of the Validator, are answered with the matching JSON-RPC error when a method throws them. For the exceptions of the application implement Kraz\JsonRpcServer\ExceptionConverterInterface (autoconfigured, or tagged kraz_json_rpc_server.exception_converter). Everything else is logged and answered with -32603 Internal error.

Middleware

A service implementing Kraz\JsonRpcServer\Middleware\MiddlewareInterface wraps the calls of every server. Tag it explicitly to pick a server or an order (the higher the priority, the further out):

services:
    App\JsonRpc\Middleware\Transactional:
        tags:
            - { name: kraz_json_rpc_server.middleware, server: admin, priority: 10 }

Security

Authentication is the job of the firewall the endpoint sits behind; the bundle only reports its outcome to the server. A permission of #[RequiresPermission] is a security attribute — a role, or anything a voter of the application decides on; the voters receive the MethodDescriptor as the subject.

An invalid credential never reaches the server: the firewall answers. To let anonymous callers reach the #[PublicAccess] methods, the endpoint itself must be open in access_control; the server then guards every other method.

JWT

Nothing specific: put the path of the server behind the firewall which authenticates the tokens, for example with LexikJWTAuthenticationBundle:

security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            jwt: ~
    access_control:
        - { path: ^/api/rpc$, roles: PUBLIC_ACCESS }

Static API keys

The bundle ships the two services the access_token authenticator of Symfony needs to authenticate static keys:

Service Role
kraz_json_rpc_server.api_key_handler token handler: finds the client a key belongs to
kraz_json_rpc_server.api_key_extractor token extractor: reads the key from the request (header, optionally the URI)

Setting it up takes three steps.

1. Declare the keys. Each entry is a client; its name becomes the user identifier the client is authenticated as, and its roles are what #[RequiresPermission] is checked against.

# config/packages/kraz_json_rpc_server.yaml
kraz_json_rpc_server:
    api_keys:
        header: X-API-Key
        keys:
            billing:    { key: '%env(RPC_KEY_BILLING)%', roles: [ROLE_RPC] }
            backoffice: { key: '%env(RPC_KEY_BACKOFFICE)%', roles: [ROLE_RPC, ROLE_BACKOFFICE] }

Keep the keys out of the repository: in the environment or in the secrets vault. The clients are not users of the application — each key authenticates as an in-memory user, no user provider is asked for it.

2. Put the endpoint behind a firewall which uses the handler. A firewall of its own, scoped to the paths of the JSON-RPC servers, keeps the keys from being accepted anywhere else:

# config/packages/security.yaml
security:
    firewalls:
        rpc:
            pattern: ^/rpc
            stateless: true
            # provider: app_users
            access_token:
                token_handler: kraz_json_rpc_server.api_key_handler
                token_extractors:
                    - kraz_json_rpc_server.api_key_extractor    # X-API-Key: <key>
                    - header                                    # Authorization: Bearer <key>
        # ... the other firewalls of the application
  • The first firewall whose pattern matches a request handles it, so this one must be listed before a broader one which would also match the path (^/api, or a firewall without a pattern).
  • When the application has more than one user provider, Symfony requires the firewall to name one in provider, even though the keys never use it. Any of them will do.
  • Leave the header extractor out if the clients only send the dedicated header.

3. Open or close the path in access_control. The firewall only establishes who is calling; whether an anonymous request may reach the endpoint at all is decided here.

security:
    access_control:
        # Anonymous callers reach the endpoint; the server refuses every method which is not #[PublicAccess].
        - { path: ^/rpc, roles: PUBLIC_ACCESS }
        # ... or: nobody without a valid key gets past the firewall.
        # - { path: ^/rpc, roles: ROLE_RPC }

Mind the order here too: the first rule which matches the path applies, so it has to come before a catch-all such as { path: ^/, roles: IS_AUTHENTICATED }.

What the client gets:

Request Answer
a valid key the calls are made as that client
a key which is not valid 401 from the firewall — the request never reaches the server
no key, path open in access_control 200; every method except the #[PublicAccess] ones answers -32001
no key, path closed in access_control 401 from the firewall
a valid key lacking a required role 200; the method answers -32003

API keys next to JWT on the same paths

When the JSON-RPC endpoints live under a path a JWT firewall already covers, and that firewall cannot be split, add access_token to it instead of creating a second one:

security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            jwt: ~
            access_token:
                token_handler: kraz_json_rpc_server.api_key_handler
                token_extractors: kraz_json_rpc_server.api_key_extractor

Two things to be aware of:

  • Do not add the header extractor here. It reads Authorization: Bearer <token>, the very header the JWT is sent in, and a JWT would be looked up as an API key and refused. With the extractor of the bundle alone the two do not overlap: a request with an X-API-Key header (or the query parameter) is an API key request, a request with a bearer token is a JWT request.
  • The keys are then accepted on every path of that firewall, not only on the JSON-RPC ones. Give the clients roles which open nothing but what they need, and let access_control or the voters of the application do the rest.

Keys in the URI, for legacy clients

A client which cannot send a header may pass its key as a query parameter of the URI. Turn it on by naming the parameter; steps 1 to 3 above stay exactly as they are, because it is the same extractor reading the key from a second place:

kraz_json_rpc_server:
    api_keys:
        query_parameter: key
        keys:
            legacy-erp: { key: '%env(RPC_KEY_LEGACY_ERP)%', roles: [ROLE_RPC] }
POST /rpc/orders?key=<key>          a call
GET  /rpc/orders?smd&key=<key>      the service mapping description of that client
  • It is off by default (query_parameter: ~): the parameter is then ignored and the caller is anonymous.
  • A header wins when a request carries both.
  • The firewall must list kraz_json_rpc_server.api_key_extractor in token_extractors — the header and query_string extractors of Symfony do not read this parameter.
  • The target of the service mapping description never contains the key.
  • A parameter which is not a plain string (?key[]=...) is not a key: the caller is anonymous.

This is not a secure way to send a credential, and it is meant for trusted networks only. A URI is recorded by web server access logs, by proxies, by the request log channel of Symfony ("Matched route ...") and by whatever made the request, and the key with it. To limit what a leaked log costs:

  • give every legacy client a key of its own, with as few roles as it needs;
  • restrict the firewall, or the web server in front of it, to the addresses of those clients where possible;
  • keep the logs which record URIs out of reach, or strip the parameter from them;
  • move a client to the header as soon as it can send one — both work at the same time.

Rate limiting

framework:
    rate_limiter:
        json_rpc:
            policy: sliding_window
            limit: 120
            interval: '1 minute'

kraz_json_rpc_server:
    servers:
        default:
            rate_limiter: json_rpc

Every call of a payload consumes a token, per user (per address for anonymous callers). A refused payload is answered with the status 429, a Retry-After header and the error -32029.

Using a server without HTTP

The servers are services: Kraz\JsonRpcServer\Server autowires the default one, Server $adminServer the one named admin, and Kraz\JsonRpcServerBundle\ServerRegistry gives all of them by name.

$result = $server->handle($json, new Context(transport: 'amqp'));

Logging

The calls are logged in the json_rpc Monolog channel: successful ones at info, errors answered to the caller at warning, unexpected exceptions at error with the exception attached.

License

This bundle is licensed under the MIT License. See the LICENSE file for details.