Skip to main content
Every request in Apivalk is associated with an AbstractAuthIdentity. This ensures that your authorization logic can always rely on an identity object being present, eliminating the need for null checks.

AbstractAuthIdentity

The base class for all identities. It defines the contract for checking authentication status, granted scopes, and permissions.

Methods

  • isAuthenticated(): bool: Returns true if the requester is authenticated.
  • getScopes(): string[]: Returns an array of scope names granted to this identity.
  • getPermissions(): string[]: Returns an array of permission names granted to this identity.
  • isScopeGranted(string $scope): bool: Helper method to check if a specific scope is present.
  • isPermissionGranted(string $permission): bool: Helper method to check if a specific permission is present.

JwtAuthIdentity

Represents a successfully authenticated user via JWT.

Usage

Typically created by the JwtAuthenticator after validating a token.
use apivalk\apivalk\Security\AuthIdentity\JwtAuthIdentity;

$identity = new JwtAuthIdentity(
    'john_doe',
    'john@example.com',
    'user-123',
    ['read:profile'],
    ['profile:view']
);

Additional Methods

  • getUsername(): ?string: Returns the username.
  • getEmail(): ?string: Returns the email.
  • getSub(): ?string: Returns the subject (sub claim).

GuestAuthIdentity

Represents an anonymous or non-authenticated requester.

Usage

By default, every request is initialized with an empty GuestAuthIdentity.
use apivalk\apivalk\Security\AuthIdentity\GuestAuthIdentity;

$identity = new GuestAuthIdentity();

Public Scopes

You can initialize a GuestAuthIdentity with default scopes. This is useful for “Public but scoped” endpoints where you want to grant certain permissions to everyone.
$identity = new GuestAuthIdentity(['public:read']);

Accessing Identity in Controllers

You can retrieve the current identity from the request object in any controller.
class MyController extends AbstractApivalkController {
    public function __invoke(ApivalkRequestInterface $request): AbstractApivalkResponse {
        $identity = $request->getAuthIdentity();
        
        if ($identity->isAuthenticated()) {
            $userId = $identity->getUserId();
            // ... logic for logged-in users
        }
    }
}