> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Identities

> Identities represent the entity making the request, whether it's an authenticated user or an anonymous guest.

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](/security/authenticator) after validating a token.

```php theme={null}
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`.

```php theme={null}
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.

```php theme={null}
$identity = new GuestAuthIdentity(['public:read']);
```

***

## Accessing Identity in Controllers

You can retrieve the current identity from the request object in any controller.

```php theme={null}
class MyController extends AbstractApivalkController {
    public function __invoke(ApivalkRequestInterface $request): AbstractApivalkResponse {
        $identity = $request->getAuthIdentity();
        
        if ($identity->isAuthenticated()) {
            $userId = $identity->getUserId();
            // ... logic for logged-in users
        }
    }
}
```
