uxf / security
Requires
- php: ^8.4
- ext-json: *
- doctrine/dbal: ^4.5
- doctrine/orm: ^3.7
- firebase/php-jwt: ^6.0 || ^7.0
- symfony/config: ^7.4 || ^8.0
- symfony/console: ^7.4 || ^8.0
- symfony/dependency-injection: ^7.4 || ^8.0
- symfony/event-dispatcher: ^7.4 || ^8.0
- symfony/http-client: ^7.4 || ^8.0
- symfony/http-foundation: ^7.4 || ^8.0
- symfony/http-kernel: ^7.4 || ^8.0
- symfony/password-hasher: ^7.4 || ^8.0
- symfony/routing: ^7.4 || ^8.0
- symfony/security-bundle: ^7.4 || ^8.0
- symfony/validator: ^7.4 || ^8.0
- twig/twig: ^3.0
- uxf/core: 3.90.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- 3.x-dev
- 3.90.2
- 3.90.1
- 3.90.0
- 3.89.3
- 3.89.2
- 3.89.1
- 3.89.0
- 3.88.0
- 3.87.2
- 3.87.1
- 3.87.0
- 3.86.0
- 3.85.1
- 3.85.0
- 3.84.4
- 3.84.3
- 3.84.2
- 3.84.1
- 3.84.0
- 3.83.1
- 3.83.0
- 3.82.0
- 3.81.8
- 3.81.7
- 3.81.5
- 3.81.4
- 3.81.3
- 3.81.2
- 3.81.0
- 3.80.3
- 3.80.2
- 3.80.0
- 3.79.3
- 3.79.2
- 3.79.0
- 3.78.7
- 3.78.2
- 3.78.0
- 3.77.9
- 3.77.8
- 3.77.7
- 3.77.5
- 3.77.4
- 3.77.3
- 3.77.2
- 3.76.3
- 3.76.2
- 3.76.0
- 3.75.12
- 3.75.10
- 3.75.9
- 3.75.5
- 3.75.3
- 3.75.0
- 3.74.4
- 3.74.2
- 3.73.6
- 3.73.5
- 3.73.4
- 3.73.3
- 3.73.2
- 3.73.0
- 3.72.2
- 3.72.1
- 3.72.0
- 3.71.0
- 3.70.5
- 3.70.4
- 3.70.3
- 3.70.2
- 3.70.0
- 3.69.12
- 3.69.7
- 3.69.6
- 3.69.5
- 3.69.3
- 3.69.1
- 3.69.0
- 3.68.5
- 3.68.4
- 3.68.3
- 3.68.2
- 3.68.1
- 3.68.0
- 3.67.3
- 3.67.0
- 3.66.0
- 3.65.3
- 3.65.2
- 3.65.0
- 3.64.4
- 3.64.3
- 3.64.2
- 3.64.1
- 3.64.0
- 3.63.1
- 3.62.4
- 3.62.3
- 3.62.2
- 3.62.0
- 3.61.7
- 3.61.6
- 3.61.5
- 3.61.3
- 3.61.2
- 3.61.1
- 3.61.0
- 3.60.12
- 3.60.11
- 3.60.10
- 3.60.8
- 3.60.7
- 3.60.5
- 3.60.3
- 3.60.0
- 3.59.0
- 3.58.8
- 3.58.5
- 3.58.4
- 3.58.2
- 3.58.1
- 3.58.0
- 3.57.12
- 3.57.10
- 3.57.7
- 3.57.6
- 3.57.1
- 3.57.0
- 3.56.3
- 3.56.2
- 3.56.1
- 3.56.0
- 3.55.9
- 3.55.8
- 3.55.7
- 3.55.5
- 3.55.0
- 3.54.5
- 3.54.3
- 3.54.2
- 3.54.0
- 3.53.7
- 3.53.3
- 3.53.2
- 3.53.1
- 3.53.0
- 3.51.2
- 3.51.0
- 3.50.6
- 3.50.5
- 3.50.3
- 3.50.2
- 3.50.1
- 3.50.0
- 3.49.2
- 3.49.1
- 3.49.0
- 3.48.0
- 3.47.2
- 3.47.0
- 3.46.11
- 3.45.3
- 3.45.2
- 3.45.1
- 3.44.6
- 3.44.5
- 3.44.4
- 3.44.3
- 3.44.2
- 3.44.0
- 3.43.2
- 3.43.0
- 3.42.0
- 3.41.2
- 3.41.1
- 3.41.0
- 3.40.4
- 3.40.3
- 3.40.2
- 3.40.1
- 3.40.0
- 3.39.4
- 3.39.3
- 3.39.2
- 3.39.1
- 3.38.0
- 3.37.1
- 3.37.0
- 3.36.3
- 3.36.2
- 3.36.0
- 3.35.5
- 3.35.4
- 3.35.2
- 3.34.3
- 3.34.0
- 3.33.0
- 3.32.4
- 3.32.3
- 3.30.1
- 3.29.1
- 3.29.0
- 3.27.3
- 3.26.0
- 3.25.5
- 3.25.4
- 3.24.2
- 3.24.1
- 3.24.0
- 3.23.3
- 3.23.1
- 3.23.0
- 3.22.0
- 3.21.4
- 3.21.3
- 3.21.0
- 3.20.0
- 3.19.4
- 3.19.3
- 3.19.2
- 3.18.0
- 3.17.4
- 3.17.3
- 3.17.1
- 3.17.0
- 3.15.6
- 3.15.5
- 3.13.2
- 3.13.0
- 3.11.3
- 3.11.0
- 3.10.1
- 3.10.0
- 3.9.2
- 3.8.2
- 3.8.1
- 3.8.0
- 3.7.3
- 3.7.1
- 3.7.0
- 3.6.0
- 3.5.0
- 3.4.0
- 3.3.0
- 3.2.4
- 3.2.3
- 3.2.2
- 3.2.1
- 3.2.0
- 3.1.4
- 3.1.3
- 3.1.2
- 3.1.1
- 3.1.0
- 3.0.4
- 3.0.3
- 3.0.2
- 3.0.1
- 3.0.0
- dev-main
This package is auto-updated.
Last update: 2026-11-19 00:27:12 UTC
README
JWT authentication for a Symfony API: password login, refresh tokens, cookie or header transport, role checks on controllers, OpenID Connect login (Google, Apple, …) and an optional OAuth 2.1 authorization server for MCP and other resource servers.
Install
$ composer req uxf/security
// config/packages/uxf.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->extension('uxf_security', [
'user_class' => User::class, // required
'base_url' => 'https://uxf.cz', // required; no trailing slash, it is also the JWT/OAuth issuer
'public_key' => '%env(AUTH_PUBLIC_KEY)%', // required
'private_key' => '%env(AUTH_PRIVATE_KEY)%', // required
'user_checker' => ActiveUserChecker::class, // required (uxf/cms sets its ActiveUserChecker), see "User checker"
// optional
'access_token_lifetime' => 'P10Y', // default 1 day
'refresh_token_lifetime' => 'P20Y', // default 1 month
'refresh_token_cookie_path' => '/api/auth', // default null = no refresh token cookie; /api/auth covers refresh and logout
'cookie_name' => 'Cookie-Name', // default Authorization - used for header + cookie
'cookie_secured' => false, // default true
'cookie_http_only' => false, // default true
'login_attempt' => [
'enabled' => true, // default true; false = no attempt recorded, no throttling
'limit' => 5, // default 5 failed logins per IP + username ...
'ip_limit' => 25, // default 25 failed logins per IP (0 = off) ...
'interval' => 900, // ... per 900 seconds
'methods' => [ // limits of other login methods, see "Login attempts and rate limiting"
'api' => [], // the limit, ip_limit and interval of the password
'totp' => ['limit' => 0, 'ip_limit' => 0, 'username_limit' => 5],
],
],
// OpenID Connect - optional
'oidc' => [
'apple' => [
'client_id' => 'xxx',
],
'facebook' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
],
'gitlab' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
],
'google' => [
'client_id' => 'xxx',
],
'microsoft' => [
'client_id' => 'xxx',
],
'mojeid' => [
'client_id' => 'xxx',
],
'seznam' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
],
'uxf' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
'app_name' => 'xxx',
],
],
// OAuth 2.1 authorization server - optional, see "OAuth 2.1" below
'oauth' => [
'enabled' => false,
],
]);
};
All lifetimes are ISO 8601 durations (DateInterval): PT1H, P1D, P30D, …
Keys
Tokens are signed with RS256. public_key and private_key are the PEM contents (not file paths), usually
from env variables:
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
Every token carries iss: <base_url> and is rejected when it does not match, so changing base_url or
rotating the key pair invalidates every issued access token, including OAuth ones. The public key is
published as a JWK set on GET /api/auth/keys (kid is fixed), so another service can verify the tokens
without sharing the private key.
Database
The bundle has its own Doctrine entities in the uxf_security schema: RefreshToken, ExternalLogin
(OIDC accounts linked to a user) and, used only with OAuth, OAuthRefreshToken and OAuthConsumedToken.
They reference the user through UserInterface, which the bundle maps to user_class via
resolve_target_entities. Generate a migration after installing or upgrading the bundle.
User provider
The bundle looks users up through UXF\Security\Service\AuthUserProvider, which the application must
implement (uxf/cms does it in UserRepository). It only finds the user, who may log in decides the user checker:
use UXF\Security\Service\AuthUserProvider;
/**
* @implements AuthUserProvider<User>
*/
final readonly class UserProvider implements AuthUserProvider
{
public function __construct(private UserRepository $userRepository)
{
}
// password login, OIDC account linking (called with the e-mail), OAuth and uxf:security:access-token
public function findByUsername(string $username): ?User
{
return $this->userRepository->findOneBy(['email' => $username]);
}
}
User checker
Who may log in is a Symfony UserCheckerInterface (uxf/cms has ActiveUserChecker: an inactive user is refused,
it is the default uxf_security.user_checker there). It runs in three places:
// config/packages/uxf_security.php: login and refresh of the default AuthService and OAuth (required)
'user_checker' => ActiveUserChecker::class,
// a second AuthService instance (e.g. the customers next to the administration) has its own one (required,
// pass it explicitly, see below)
$services->set('app_auth_service', AuthService::class)
// ...
->arg('$userChecker', service(ActiveUserChecker::class));
// config/packages/security.php: every request (recommended), each firewall with the tokens of uxf/security
'admin' => [
'stateless' => true,
'custom_authenticators' => [Authenticator::class],
'user_checker' => ActiveUserChecker::class,
],
A rule of one audience only (e.g. only an employee gets into the administration, the customers log in through the second instance) is a checker of its own that calls the common one first:
final readonly class EmployeeUserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user): void
{
$this->activeUserChecker->checkPreAuth($user);
}
public function checkPostAuth(UserInterface $user, ?TokenInterface $token = null): void
{
$employee = $this->employeeRepository->findByUser($user)
?? throw new CustomUserMessageAccountStatusException('No access to the administration');
// on the firewall: the employee stays with the token for the rest of the request
$token?->setAttribute('employee', $employee);
}
}
AuthService::login()andrefreshToken()callcheckPreAuth()andcheckPostAuth()(without a token). A refusal (AccountStatusException) is403at login and401at refresh, the message of aCustomUserMessageAccountStatusExceptionreaches the client, with its placeholders (message data) filled in. A refused login is a failedLoginAttempt(FORBIDDEN). OAuth (authorization code, refresh) answersinvalid_grant.AuthService::checkUser($user)runs the checker for a login of your own, beforegenerateAuthResponse(). The OIDC login uses it, a refusal there is a failedLoginAttemptand ends on the error page of the flow.- The
user_checkerof the firewall runs it on every request, so a token issued before the user was refused stops working at once: the request continues anonymously (protected routes answer401), the OAuth resource server answers401 invalid_token. Without it a refused user keeps access until the access token expires. It runs for every request, keep it cheap: the firewall user provider loads the user anyway, so a check that only reads the loaded entity (isActive()) adds no query. - Pass
$userCheckerof a second instance explicitly. When no firewall has auser_checkerof its own, Symfony registers the autowiring aliasUserCheckerInterface->security.user_checker, which refuses nobody, and an instance without the argument gets it silently. Security::login(), whichAuthService::login()calls, runs the user checker of the firewall of the current request too, so the login of each instance runs on the firewall of its own tokens.uxf:security:access-tokenand personal tokens do not run the checker when they are issued, the firewall refuses such a token of a refused user anyway.
Login event
UXF\Security\Event\LoginUserEvent (user, method, audience) is dispatched when a user logs in: password login
of every AuthService instance (password), OIDC login (oidc:<provider>) and OAuth authorization code exchange
(oauth, audience null); the constants are UXF\Security\Service\LoginMethod::Password,
LoginMethod::oidc($provider) and LoginMethod::OAuth. It runs after every check passed and before the tokens
are issued, not on a token refresh nor for tokens issued without a login (generateAuthResponse(),
uxf:security:access-token). It is the place for side effects of a login; uxf/cms sets the last login time
there (LastLoginListener).
Symfony security config - recommended
The access token sub is UserInterface::getUserIdentifier(), and the Symfony user provider loads the user
by it on every request, so property must be the field getUserIdentifier() returns.
// config/packages/security.php
use UXF\Security\Service\Authenticator;
return static function (ContainerConfigurator $config): void {
$config->extension('security', [
'password_hashers' => [
\UXF\CMS\Entity\User::class => 'auto',
],
'providers' => [
'provider' => [
'entity' => [
'class' => \UXF\CMS\Entity\User::class,
'property' => 'email', // BC break in 3.68 (id -> email)
],
],
],
'firewalls' => [
'main' => [
'stateless' => true,
'custom_authenticators' => [Authenticator::class],
// required, see "User checker"
'user_checker' => \UXF\CMS\Security\ActiveUserChecker::class,
],
],
'access_control' => [
['path' => '^/api/auth', 'roles' => 'PUBLIC_ACCESS'],
['path' => '^/api/admin', 'roles' => 'ROLE_ADMIN'],
],
]);
};
Authenticator reads the token from the header named cookie_name (default Authorization, an optional
Bearer prefix is stripped) or from the cookie of the same name. It accepts only tokens issued by the
login (aud: user, another one with more token audiences); OAuth access tokens are
accepted only by the resource server firewall.
Login, refresh, logout
POST /api/auth/login {"username": "...", "password": "..."}
POST /api/auth/refresh-token {"refreshToken": "<uuid>"} or empty body with the refresh token cookie
GET /api/auth/logout ?redirect=/some-path (optional, relative paths only)
GET /api/auth/keys JWK set of the public key
Login and refresh return the same body and set the same cookies:
{"accessToken": "<jwt>", "refreshToken": "<uuid>"}
| Cookie | Content | Notes |
|---|---|---|
<cookie_name> | access token | HttpOnly per cookie_http_only, expires with the token |
<cookie_name>-Expire | expiry as a Unix timestamp | readable by JavaScript, so the frontend knows when to refresh |
uxf_auth_refresh_token | refresh token | only when refresh_token_cookie_path is set, always HttpOnly, sent only to that path |
A frontend that stores no tokens itself sets refresh_token_cookie_path to /api/auth and calls the
refresh endpoint with an empty body. The path must cover /api/auth/logout as well, otherwise logout cannot
revoke the token (see below). A mobile app or another API client keeps refreshToken
from the body instead and sends the access token in the header.
Refresh tokens rotate: a refresh deletes the used token and issues a new one with a full
refresh_token_lifetime, so an active user stays signed in indefinitely and an idle one is signed out
after refresh_token_lifetime. Of parallel refreshes with the same token exactly one succeeds and the others
get 401, so a frontend with several tabs or parallel requests must refresh once and share the result.
Errors:
400 INVALID_CREDENTIALSfor an unknown user, a user without a password (e.g. created by OIDC) and a wrong password alike. For the first two the password is still verified against a dummy hash made by the same hasher, so the response time does not reveal whether the account exists.429 TOO_MANY_REQUESTSwhen the login rate limit is exceeded.401when the refresh token is unknown, expired or missing.
Logout clears the cookies (the refresh token cookie with refresh_token_cookie_path) and dispatches
LogoutUserEvent. When the browser sends the refresh token cookie, i.e. when refresh_token_cookie_path
covers /api/auth/logout, the token is also deleted from the database. Otherwise, and for clients that keep
the refresh token themselves, it stays valid until it is used or expires.
Login attempts and rate limiting
Every password login and every OIDC login (a refusal of the user checker included) is recorded in
uxf_security.login_attempt (LoginAttempt): time, method (password, oidc:<provider>), username (trimmed
and lowercased), client IP, user agent, result (pending, success, failure, throttled), the error code of
a failure and the user whenever the account exists, failed and throttled attempts included (null for an unknown
username). It is an audit log and the data source of the rate limit. With the indexes (username, ip, created_at) and
(ip, created_at) the per IP + username and the per IP limit read only the window, not the whole history. The per
username limit over all IPs (off for a password) reads all index entries of the username. The index of the
user_id foreign key finds the attempts of a user, the failed ones included.
The user is looked up before the limit is checked, so a throttled request still calls
AuthUserProvider::findByUsername() (the database, an LDAP, …), and a 429 of an existing account takes a few
microseconds longer than of an unknown one.
Failed password logins are throttled within interval seconds (sliding window):
- per IP + username:
limitfailures since the last successful login of the same key, - per IP over all usernames:
ip_limitfailures (password spraying); a success does not reset it.
A password attempt is written as pending and committed before the limit is counted, so parallel attempts
see each other and the limit holds exactly, across app instances too. A request that fails before the result
is written stays pending and counts as a failure. A throttled attempt is recorded as throttled and does
not count. The rows must not be written inside a request transaction that is rolled back on an exception,
otherwise the failures vanish and the limit is never reached.
The password limit sits in AuthService::login(), not in the controller: a custom controller or a GQL
mutation calling AuthService::login() is recorded and throttled the same way. It takes the request for the
client IP and user agent:
// controller: Request $request as an argument; GQL mutation: #[Inject] Request $request
$authResponse = $authService->login($request, new LoginRequestBody($username, $password));
Do not wrap it in another LoginAttemptService::attempt() (the attempt would count twice) and do not swallow its 429 in a catch (BasicException)
(e.g. a fallback to a legacy password check), that bypasses the limit. After a password reset log the user in with
Security::login($user) + AuthService::generateAuthResponse($user, null), not with login(), which would
refuse a throttled account even with the new password.
Every method counts only its own attempts and has its own LoginLimit (per IP + username, per IP, per username
over all IPs, interval). password takes limit, ip_limit and interval, without the per username limit
(anyone could lock any account out). Another method, e.g. a second factor or an API login with a client secret,
calls the same service and gets its limit in login_attempt.methods: limit, ip_limit and interval left
out are the ones of the password, username_limit is off unless set (0 turns any of them off). A method
without an entry is recorded only. password cannot be set in methods. attempt() records the attempt, throttles it (429 over the limit, the closure does not
run) and runs the verification. The closure returns the result of the login (an object, e.g. AuthResponse)
and throws a BasicException when the credentials are refused, its error code is the failure reason. Any other
exception leaves the attempt pending (counts as a failure). It must not return bool, a refused code would be
recorded as a success: PHPStan reports it (@template T of object). attempt() returns the value of the closure:
use UXF\Security\Service\LoginAttempt\LoginAttemptSubject;
$authResponse = $loginAttemptService->attempt(
// client IP + user agent of the request; $user: the account when it exists, null otherwise
LoginAttemptSubject::fromRequest($request, 'totp', $username, $user),
function () use ($user, $code): AuthResponse {
if (!$this->totp->verify($user, $code)) {
throw BasicException::badRequest('Invalid code', 'INVALID_CODE');
}
return $this->authService->generateAuthResponse($user, null);
},
);
IP address, user agent and username are personal data. Nothing deletes the rows yet, keep the retention
in the application. With enabled: false nothing is recorded and nothing is throttled, attempt() only runs
the closure.
Behind a reverse proxy or a load balancer set framework.trusted_proxies (and trusted_headers). Otherwise
Request::getClientIp() is the proxy's address for every client: the IP + username limit becomes a per
username limit, the IP limit applies to all clients together, and anyone can lock any account out for
interval seconds with a few wrong passwords.
Access token from the command line
bin/console uxf:security:access-token <username>
Prints an access token for the user (lifetime access_token_lifetime) without creating a refresh token
and without running the user checker. Handy for tests and scripts; anyone who can run it can
sign in as anyone.
More token audiences
Access tokens carry aud: user. An application with two kinds of users (e.g. the admin and customers of
the web) defines another AuthService with its own audience, cookie and lifetimes, and an Authenticator
for it. Every Authenticator accepts only its own audience, so a customer token is refused in the admin
firewall and the other way round:
$services->set('app_auth_service', AuthService::class)
->arg('$accessTokenLifetime', 'P3M')
->arg('$refreshTokenLifetime', 'P6M')
->arg('$refreshTokenCookiePath', null)
->arg('$cookieName', 'X-Authorization')
->arg('$cookieSecured', true)
->arg('$cookieHttpOnly', true)
->arg('$audience', 'app');
$services->set('app_authenticator', Authenticator::class)
->arg('$cookieName', 'X-Authorization')
->arg('$audience', 'app');
// a controller or a GQL mutation issuing customer tokens
$services->set(AppLoginMutation::class)->arg('$authService', service('app_auth_service'));
// security.php
'firewalls' => [
'app' => ['pattern' => '^/api/app', 'stateless' => true, 'custom_authenticators' => ['app_authenticator']],
'main' => ['pattern' => '^/', 'stateless' => true, 'custom_authenticators' => [Authenticator::class]],
],
A refresh token remembers its audience and only the AuthService of the same audience refreshes it:
/api/auth/refresh-token (the default instance, user) answers 401 to a refresh token of app, it never
turns it into a user token. Refresh tokens of another audience need their own endpoint calling
refreshToken() of their instance. Logout revokes a refresh token of any audience. The default commands and
the OIDC login issue user tokens.
Authorization
Put UXF\Core\Attribute\Security on a controller method, with one role or a list of roles (any of them is
enough). Roles are values of your own backed enum:
enum UserRole: string
{
case PUBLIC = 'PUBLIC'; // anyone, also anonymous
case LOGGED = 'LOGGED'; // any signed-in user
case ROLE_ADMIN = 'ROLE_ADMIN'; // anything else goes to Security::isGranted()
}
use UXF\Core\Attribute\Security;
final readonly class ArticleDeleteController
{
#[Security([UserRole::ROLE_ADMIN, UserRole::ROLE_EDITOR])]
#[Route('/api/admin/article/{id}', methods: 'DELETE')]
public function __invoke(#[Entity] Article $article): void
{
}
}
An anonymous user gets 401, a signed-in user without the role 403. The same check (RoleChecker) is
used by uxf/graphql for queries and mutations.
Events
LogoutUserEvent
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use UXF\Security\Event\LogoutUserEvent;
#[AsEventListener(LogoutUserEvent::class)]
final readonly class LogoutUserListener
{
public function __invoke(LogoutUserEvent $event): void
{
// edit response cookies/headers
...
}
}
NewUserEvent
Dispatched by the OIDC login when no user matches, see Create new user.
OAuth 2.1
The bundle can act as an OAuth 2.1 authorization server for the resource servers of the application. It is a generic server; MCP servers (Claude Code, claude.ai connectors, ...) are its first consumer and the source of the requirements.
Endpoints (all under the bundle's /api/auth prefix except the RFC-mandated well-known documents):
GET /.well-known/oauth-authorization-server # RFC 8414
GET /.well-known/oauth-protected-resource/<path> # RFC 9728, e.g. /.well-known/oauth-protected-resource/mcp/cms
GET /api/auth/oauth/authorize # PKCE S256 + state + resource required; anonymous user -> login_url?redirect=...
POST /api/auth/oauth/authorize # consent form submit
POST /api/auth/oauth/token # authorization_code, refresh_token (rotation)
Clients register either through a Client ID Metadata Document (an HTTPS client_id URL, used by Claude Code
and claude.ai connectors) or up front in oauth.clients. Dynamic Client Registration (RFC 7591) is not
implemented: MCP deprecated it in favour of CIMD.
Fetching a metadata document means following a URL a stranger supplied, so it is guarded: HTTPS only,
standard port, no redirect is followed without checking the new target again, the connection is pinned to
the address that was checked (DNS rebinding), private, reserved and carrier grade NAT addresses are
refused for both IPv4 and IPv6, and the body is capped at 64 kB while being read. cimd.allowed_hosts
narrows which hostnames may be fetched at all; it does not exempt them from the address check. There is
no rate limit on this outgoing request yet, so it is still the cheapest way to make the server do work.
The OAuth issuer is always base_url, taken verbatim (RFC 8414 serves its metadata from the issuer root),
so it must not end with a slash: a trailing one would put the metadata at https://uxf.cz//.well-known/….
The oauth node has its own three lifetimes, on purpose: the root ones belong to the cookie/API login,
where a long value is a reasonable choice, and an OAuth access token cannot be revoked once it is signed.
There is a single scope, api, and it is not configurable: it carries no authorization of its own,
what a user may do is decided by their roles, exactly as in the REST API. The authorization server
metadata also advertises offline_access, which is how clients ask for a refresh token; one is issued
either way.
oauth.resources is the allowlist of resource servers this application serves. It decides which resource
a client may ask a token for (so the server never mints a token for a foreign audience), which paths the
resource server firewall accepts, and what the protected resource metadata describes. Each entry must be an
absolute http(s) URL without a fragment, query string or userinfo, and the list may not be empty once OAuth
is on.
// config/packages/uxf.php
$containerConfigurator->extension('uxf_security', [
// ...
'oauth' => [
'enabled' => true,
'access_token_lifetime' => 'PT1H', // default 1 hour
'refresh_token_lifetime' => 'P30D', // default 30 days
'authorization_code_lifetime' => 'PT60S', // default 60 seconds
'login_url' => '/login', // your frontend login; must redirect back to ?redirect=<url> after login
'resources' => ['https://uxf.cz/mcp/cms'], // required; canonical URLs of your resource servers (RFC 8707)
'cimd' => [ // Client ID Metadata Documents (Claude Code, claude.ai)
'enabled' => true,
'allowed_hosts' => [], // e.g. ['claude.ai'] for internal deployments
],
'clients' => [ // pre-registered clients
'my-frontend' => [
'name' => 'My frontend',
'redirect_uris' => ['https://uxf.cz/oauth/callback'],
'secret' => '%env(OAUTH_MY_FRONTEND_SECRET)%', // null = public client
'consent_required' => false,
],
],
],
]);
Resource server firewall of the application (here an MCP server under /mcp/, but the pattern is the same
for any protected resource):
// config/packages/security.php
'firewalls' => [
'mcp' => [
'pattern' => '^/mcp/',
'stateless' => true,
'access_token' => [
'token_handler' => \UXF\Security\Service\OAuth\ResourceServer\AccessTokenHandler::class,
'token_extractors' => 'header',
'failure_handler' => \UXF\Security\Service\OAuth\ResourceServer\AuthenticationFailureHandler::class,
],
'entry_point' => \UXF\Security\Service\OAuth\ResourceServer\AuthenticationEntryPoint::class,
],
'main' => [ /* your existing firewall with UXF\Security\Service\Authenticator */ ],
],
'access_control' => [
['path' => '^/mcp/', 'roles' => 'ROLE_USER'],
],
Some clients cannot do OAuth at all and only send a fixed header (Continue, the OpenAI agent APIs,
mcp-remote --header). A signed-in user issues such a token for themselves, so build a button for it into
your UI and let them paste the result into the client:
POST /api/auth/personal-token # behind your cookie firewall, uses the caller's identity and roles
{"resource": "https://uxf.cz/mcp/cms", "lifetime": "P30D"}
→ {"accessToken": "...", "resource": "https://uxf.cz/mcp/cms", "expiresAt": "..."}
lifetime is optional and capped by oauth.refresh_token_lifetime, which is also the default. The token
carries client_id: static so it is recognisable in logs, and it has no refresh token, so it ends only by
expiring or by a key rotation. uxf:security:access-token is unrelated and keeps issuing API tokens only.
OAuth refresh tokens live in their own table, separate from the ones the cookie login issues, because
their lifetimes differ. They rotate: using one deletes it and issues a replacement, so the same token
never works twice. The replacement inherits the expiry of the token it replaced, which means a grant
lasts exactly refresh_token_lifetime from when it was made however often it is refreshed; after that
the client has to authorize again. Rotation alone is what RFC 9700 §2.2.2 asks for, so a token presented
twice is simply unknown here and is not treated as evidence of theft.
An OAuth access token lasts oauth.access_token_lifetime, an hour by default. Nothing can revoke a
signed access token, not even deleting the refresh token it came with, so raising that value means
a stolen token stays usable for as long as it says.
Authorization codes and consent tokens are single use, enforced by a primary key rather than by a cache, so it holds across instances.
Nothing is deleted automatically, so schedule the cleanup command. It removes only rows whose lifetime
has passed, which no lookup can reach any more: expired RefreshToken, OAuthRefreshToken and
OAuthConsumedToken rows.
bin/console uxf:security:token-cleanup [--dry-run]
Tokens: API/cookie tokens have aud: "user", OAuth access tokens have aud: <resource URL> and header
typ: at+jwt; each firewall accepts only its own kind. Security::getToken()->getAttribute('client_id')
gives the OAuth client inside the resource server. /.well-known/* and /api/auth/oauth/token must be
reachable anonymously; /api/auth/oauth/authorize must be behind the cookie firewall with PUBLIC_ACCESS
so that the anonymous user can be redirected to login_url.
Example: connecting Claude Code to an MCP server of your application
End-to-end example for an application on https://app.example.com exposing its MCP tools under /mcp/cms
(served by symfony/mcp-bundle or anything else behind the resource server firewall above).
1. Enable the authorization server and declare what it protects. The resource is the canonical URL of
the endpoint, and base_url doubles as the OAuth issuer:
// config/packages/uxf.php
$containerConfigurator->extension('uxf_security', [
'user_class' => User::class,
'base_url' => 'https://app.example.com', // no trailing slash
'public_key' => '%env(AUTH_PUBLIC_KEY)%',
'private_key' => '%env(AUTH_PRIVATE_KEY)%',
'oauth' => [
'enabled' => true,
'login_url' => '/login', // must redirect back to ?redirect=<url> after login
'resources' => ['https://app.example.com/mcp/cms'],
],
]);
Add the resource server firewall for ^/mcp/ as shown above, and keep /.well-known/* and
/api/auth/oauth/token anonymous.
2. Add the server to Claude Code. No client registration is needed: the metadata advertises
client_id_metadata_document_supported, so Claude Code identifies itself with its own Client ID Metadata
Document.
claude mcp add --transport http cms https://app.example.com/mcp/cms
The first call gets a 401 with WWW-Authenticate pointing at
/.well-known/oauth-protected-resource/mcp/cms. From there Claude Code finds the authorization server,
opens a browser for login and consent, and receives a token whose aud is that one resource, so it is
useless anywhere else. A refresh token comes along because offline_access is advertised.
3. Optional: pre-register the client instead. Use this when you do not want the server fetching a remote metadata document, or when you want the client to be auditable. Loopback redirect URIs are matched without the port (RFC 8252 §7.3), so register the portless form and let Claude Code pick a random one:
'clients' => [
'claude-code' => [
'name' => 'Claude Code',
'redirect_uris' => ['http://localhost/callback'],
'consent_required' => false,
],
],
claude mcp add --transport http --client-id claude-code cms https://app.example.com/mcp/cms
For a confidential client add --client-secret, which prompts for it, or pass it in MCP_CLIENT_SECRET.
4. Clients that cannot do OAuth. Issue a personal token as the signed-in user and hand it over as a fixed header:
curl -X POST https://app.example.com/api/auth/personal-token \
-b "Authorization=<your login cookie>" \
-H 'Content-Type: application/json' \
-d '{"resource": "https://app.example.com/mcp/cms", "lifetime": "P30D"}'
claude mcp add --transport http cms https://app.example.com/mcp/cms \
--header "Authorization: Bearer <accessToken from the response>"
OpenID Connect
Sign in with an external identity provider. Enable a provider in the oidc config, register the callback
URL at the provider and link to the login URL from the frontend:
# login (redirect after login, default /; relative paths only, anything else falls back to /)
https://domain.com/api/auth/oidc/<provider>/login?redirect=/some-path
# callback - register this one at the provider, it is built from base_url
https://domain.com/api/auth/oidc/<provider>/callback
Flow
/loginredirects to the provider and storesstate,nonceand the redirect path in short-lived cookies (10 minutes,HttpOnly). Aform_postcallback (apple, google, microsoft, mojeid) is a cross-site POST, so these cookies areSecure+SameSite=Noneand the flow works only over https or on localhost. Aquerycallback (facebook, gitlab, seznam, uxf) is a top-level GET, these cookies areSameSite=LaxandSecurefollowscookie_secured, so they work over plain http too.- The provider sends the user back to
/callback(GET or POST). The bundle checksstateagainst the cookie (CSRF), then verifies the ID token signature against the provider's JWKS, itsaud(yourclient_id),isswhere the provider configuration lists issuers andnonce(replay). A provider that returns no ID token from the code exchange (seznam) is asked its userinfo endpoint instead. - The user is found or created (see below),
AuthService::checkUser()runs the user checker,LoginUserEventis dispatched and the same cookies as after a password login are set. The flow cookies are cleared and the browser is redirected. The login is recorded as a login attempt (oidc:<provider>), a refusal of the user checker as a failed one.
A failed check, a refusal of the user checker included, renders @UXFSecurity/oidc/error.html.twig with status
400 and clears the flow cookies.
Which user signs in
- An
ExternalLoginwith the same provider andsubexists: its user. - Otherwise a user returned by
AuthUserProvider::findByUsername(<e-mail from the ID token>)is linked to the external account. - Otherwise
NewUserEventis dispatched and the user it returns is persisted and linked.
A login whose email_verified is false is refused. When the provider does not send the claim at all, the
e-mail is trusted, so step 2 links an existing account to whoever controls that e-mail at the provider.
Enable only providers that verify e-mail addresses.
Create new user
use Nette\Utils\Random;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use UXF\CMS\Entity\User;
use UXF\Security\Service\OIDC\NewUserEvent;
#[AsEventListener(NewUserEvent::class)]
final readonly class NewUserListener
{
public function __invoke(NewUserEvent $event): void
{
// $event->oidcInfo: providerName, sub, email, emailVerified, claims (all claims of the ID token)
$event->user = new User($event->oidcInfo->email, '', Random::generate());
}
}
Without a listener that sets $event->user the login of a new user ends with a LogicException.
Providers & URLs
- apple
- gitlab
- microsoft
- mojeid
- seznam
- uxf (
https://sso.uxf.cz,app_nameis the application slug there)
Custom provider
Implement OIDCProvider; the OIDCProviderTrait does the redirect and the token exchange from the
returned Configuration. The class is tagged automatically, its name in the URL is the #[AsTaggedItem]
index. Register it as a service yourself, not in the oidc config (that one accepts only the built-in
providers):
use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;
use UXF\Core\Type\Email;
use UXF\Security\Service\OIDC\Configuration;
use UXF\Security\Service\OIDC\OIDCConnector;
use UXF\Security\Service\OIDC\OIDCInfo;
use UXF\Security\Service\OIDC\Provider\OIDCProvider;
use UXF\Security\Service\OIDC\Provider\OIDCProviderTrait;
#[AsTaggedItem(index: self::NAME)]
final readonly class FakeProvider implements OIDCProvider
{
use OIDCProviderTrait;
public const string NAME = 'fake';
public function __construct(
private OIDCConnector $connector,
private string $clientId,
) {
}
public function getConfiguration(): Configuration
{
return new Configuration(
providerName: self::NAME,
clientId: $this->clientId,
clientSecret: null,
responseType: 'id_token',
responseMode: 'form_post',
scope: 'openid email',
authorizationUrl: 'https://uxf.cz',
jwksUrl: 'https://uxf.cz',
tokenUrl: 'https://uxf.cz',
userInfoUrl: null,
// optional, without it the claims are mapped by default (sub, email, email_verified)
oidcInfoCreator: fn (array $userInfo) => new OIDCInfo(
providerName: self::NAME,
sub: $userInfo['sub'],
email: Email::of($userInfo['custom_email']),
emailVerified: $userInfo['custom_verified'],
claims: $userInfo,
),
// accepted "iss" claims of the ID token, [] = not checked
issuers: ['https://uxf.cz'],
);
}
}
// config/services.php
$services->set(FakeProvider::class)
->arg('$clientId', '%env(FAKE_OIDC_CLIENT_ID)%');