---
url: https://laranex.vercel.app/laravel-biometric-auth/usage.md
description: >-
  Register a device public key, issue a challenge, verify the signed challenge
  and revoke biometrics.
---

# Usage

## How it works

The private key never leaves the device. Your API stores only the public key and proves the device holds the private key by asking it to sign a one-time challenge.

## Preparing the model

```php
use Laranex\LaravelBiometricAuth\Traits\HasBiometrics;

class User extends Authenticatable
{
    use HasBiometrics;
}
```

Biometrics are stored with the model's morph class (`getMorphClass()`), so `Relation::morphMap()` aliases are respected.

## Registering a biometric

Store the device's base64-encoded public key (PEM or DER). Only EC P-256, EC P-384, Ed25519 and 2048 to 4096-bit RSA keys are accepted, given as strict base64 of at most 8192 characters; anything else throws `InvalidPublicKeyException` (see [Accepted public keys](/laravel-biometric-auth/configuration#accepted-public-keys)).

```php
$biometric = $user->createBiometric($publicKeyBase64);

$biometric->id; // UUID the device keeps
```

A model can have at most `max_per_user` active biometrics (10 by default, `BIOMETRIC_AUTH_MAX_PER_USER`). Once it has that many, `createBiometric()` throws `TooManyBiometricsException`; revoke one first.

### Enrolling a device safely

A registered key keeps working after the bearer token that enrolled it is revoked, so a stolen token alone must not be enough to enroll one. Ask for the current password (or an OTP) in the same request, tell the user a new device was added so an unexpected enrollment gets noticed, and throttle the route:

```php
Route::post('/biometrics', function (Request $request) {
    $request->validate(['password' => ['required', 'current_password:sanctum']]);

    $biometric = $request->user()->createBiometric($request->string('public_key')->toString());

    // Your own notification: "A new device can now sign in to your account."
    $request->user()->notify(new BiometricRegistered($biometric));

    return ['biometric_id' => $biometric->id];
})->middleware(['auth:sanctum', 'throttle:5,1']);
```

`BiometricRegistered` stands for a notification of your own; the package doesn't ship one.

Every biometric of a model, revoked ones included, is available through the `biometrics()` morph-many relation. The `active()` scope keeps only biometrics that are not revoked:

```php
$user->biometrics()->active()->get();
```

`public_key`, `challenge`, `authenticable_id` and `authenticable_type` are hidden when a `Biometric` is serialized. Only `public_key` is mass assignable: the owner, the challenge and the revoked flag are set by the package.

## Issuing a challenge

```php
use Laranex\LaravelBiometricAuth\Facades\LaravelBiometricAuth;

$biometric = LaravelBiometricAuth::getBiometric($biometricId);

$biometric->challenge; // the device signs this
```

The challenge is a random 64-character hex string. It is kept until it is verified or expires, so calling `getBiometric()` twice before the device answers returns the same challenge. A challenge expires `challenge.ttl` seconds (5 minutes by default) after it was issued; the next `getBiometric()` call then issues a fresh one.

Biometric ids are UUIDs: any other id throws `BiometricNotFoundException` without querying the database.

## Verifying the signature

The device signs the challenge with its private key and sends the signature in standard base64 (a signature that is not valid base64 counts as a failed attempt):

```php
use Laranex\LaravelBiometricAuth\Models\Biometric;

$verified = LaravelBiometricAuth::verifyBiometric(
    $biometricId,
    $signatureBase64,
);

if ($verified) {
    // the model that registered the biometric
    $user = Biometric::find($biometricId)->instance;
}
```

Challenges are single-use: a successful verification clears the challenge, so a captured signature cannot be replayed. The challenge is consumed atomically, so when the same signature arrives twice at once only one request is verified. The next `getBiometric()` call issues a fresh one. An expired challenge is cleared and `verifyBiometric()` throws `BiometricChallengeNotFoundException`. A failed verification keeps the challenge so the device can retry, up to `challenge.max_attempts` failed attempts (5 by default, see [Configuration](/laravel-biometric-auth/configuration)); after that the challenge is cleared, `verifyBiometric()` throws `BiometricChallengeNotFoundException` and the client must call `getBiometric()` for a new one.

To resolve the service without the facade, use the container: `app(\Laranex\LaravelBiometricAuth\LaravelBiometricAuth::class)`.

## Revoking

Revoke one of the model's active biometrics so it can no longer be challenged or verified:

```php
$user->revokeBiometric($biometricId);
```

Revoke every device when the password changes or the account may be compromised. `revokeAllBiometrics()` revokes every active biometric of the model and returns how many it revoked:

```php
$revoked = $user->revokeAllBiometrics();
```

## Exceptions

All exceptions live in `Laranex\LaravelBiometricAuth\Exceptions`.

| Exception | HTTP status | Thrown when |
|---|---|---|
| `BiometricNotFoundException` | `404` | `getBiometric()` / `verifyBiometric()` get an unknown, revoked or non-UUID biometric id, or `revokeBiometric()` gets a biometric that does not exist, is already revoked or belongs to another model |
| `BiometricChallengeNotFoundException` | `422` | `verifyBiometric()` is called with no pending challenge: none was issued, it was consumed by a successful verification, it was cleared after too many failed attempts, or it expired |
| `InvalidPublicKeyException` | `422` | `createBiometric()` or `verifyBiometric()` cannot load the public key, or it is not an accepted type or size |
| `TooManyBiometricsException` | `422` | `createBiometric()` is called on a model that already has `max_per_user` active biometrics |

They extend `Laranex\LaravelBiometricAuth\Exceptions\BiometricException`. The status is also the exception code (`getCode()`) and is returned by `getStatusCode()`; passing a custom 4xx/5xx code to the constructor overrides it.

The exceptions are [renderable](https://laravel.com/docs/errors#renderable-exceptions): when the request expects JSON (an API call with `Accept: application/json`), an uncaught exception becomes a JSON error with that status:

```json
{ "message": "Biometric not found" }
```

Other requests fall through to your application's exception handler. Catch the exceptions, or register your own renderer with `$exceptions->render()` (Laravel 11+) or `$this->renderable()` in the exception handler (Laravel 10), to change the response.
