Skip to main content
In Apivalk, authorization is based on Scopes rather than generic roles. While a role like ROLE_ADMIN says who someone is, a scope like users:write says what they can do. This aligns with modern OAuth2 and OpenAPI standards.

ScopeInterface

The contract for all scope objects.

Methods

  • getName(): string: Returns the unique string identifier for the scope (e.g., read:orders).
  • getDescription(): ?string: Returns an optional human-readable description. This is used when generating OpenAPI documentation.

Scope Value Object

A standard implementation of ScopeInterface.

Usage

use apivalk\apivalk\Security\Scope;

$readScope = new Scope('read:products', 'Allows reading product details');
echo $readScope->getName(); // 'read:products'

Why use Objects instead of Strings?

Using objects for scopes provides several benefits over simple strings:
  1. Type Safety: You can type-hint ScopeInterface in your methods.
  2. Metadata: You can attach descriptions, which are automatically included in your generated OpenAPI security definitions.
  3. Extensibility: You can create custom scope classes that hold additional logic or metadata.

Defining Scopes on Routes

When defining a Route, you use Scope objects within a SecurityRequirementObject.
use apivalk\apivalk\Router\Route;
use apivalk\apivalk\Security\Scope;
use apivalk\apivalk\Documentation\OpenAPI\Object\SecurityRequirementObject;

$route = new Route('/orders', new PostMethod(), 'Create order', [], [
    new SecurityRequirementObject('OAuth2', [
        new Scope('orders:write', 'Permission to create new orders')
    ])
]);
When this route is converted to OpenAPI JSON, it will correctly include the scope names and descriptions in the security requirement section.