### Install Laravel Webauthn with Composer Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Install the package using Composer. ```sh composer require asbiin/laravel-webauthn ``` -------------------------------- ### GET /webauthn/keys/create Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Displays the page for registering a new WebAuthn key. This route renders the registration form for adding a new authenticator. ```APIDOC ## [GET] /webauthn/keys/create ### Description The register key page. ### Method GET ### Endpoint /webauthn/keys/create ### Parameters None ### Response #### Success Response (200) Returns the registration page HTML. #### Response Example (HTML content) ``` -------------------------------- ### GET webauthn.store.options Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Retrieves the publicKey challenge for the WebAuthn browser registration. This is optional if the challenge is already provided. ```APIDOC ## [GET] webauthn.store.options ### Description Retrieves the publicKey challenge for the WebAuthn browser registration. This is optional if the challenge is already provided. ### Method GET ### Endpoint webauthn.store.options ### Response #### Success Response (200) - **publicKey** (object) - The publicKey challenge for the WebAuthn registration #### Response Example ```json { "publicKey": {} } ``` ``` -------------------------------- ### Hosts file entry for homestead.test Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Add the site domain and network IP to the hosts file so the browser can resolve the domain. This is part of the Homestead setup for WebAuthn. ```text 192.168.254.2 homestead.test ``` -------------------------------- ### JSON response example for successful authentication Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Shows the JSON structure returned when authentication succeeds and a JSON response is requested. The 'callback' field contains the target URL from the 'webauthn.redirects.login' configuration. ```javascript { result: true, callback: `webauthn.redirects.login` target url, } ``` -------------------------------- ### GET webauthn.register Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Opens the registration page for a new WebAuthn key. The page view can be customized using Webauthn::registerViewResponseUsing or the configuration file. ```APIDOC ## [GET] webauthn.register ### Description Opens the registration page for a new WebAuthn key. The page view can be customized using Webauthn::registerViewResponseUsing or the configuration file. ### Method GET ### Endpoint webauthn.register ### Response #### Success Response (200) - **view** (blade) - The registration page view (default: webauthn::register) #### Response Example ```html ``` ``` -------------------------------- ### Full configuration example (config/webauthn.php) Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/configuration.md Complete configuration array for the Laravel WebAuthn package. Includes all options with defaults and environment variable usage. The cache driver must support cross-request storage; 'array' or 'null' drivers break the flow. ```php // config/webauthn.php return [ 'enable' => true, 'guard' => 'web', 'username' => 'email', 'prefix' => 'webauthn', 'domain' => null, 'middleware' => ['web'], 'model' => \LaravelWebauthn\Models\WebauthnKey::class, 'limiters' => ['login' => null], 'redirects' => [ 'login' => '/dashboard', 'register' => '/profile', 'key-confirmation' => null, ], 'views' => [ 'authenticate' => 'webauthn::authenticate', 'register' => 'webauthn::register', ], 'log' => null, 'session_name' => 'webauthn_auth', 'challenge_length' => 32, 'timeout' => 60000, 'extensions' => [], 'icon' => env('WEBAUTHN_ICON'), 'attestation_conveyance' => 'none', 'public_key_credential_parameters' => [ \Cose\Algorithms::COSE_ALGORITHM_ES256, \Cose\Algorithms::COSE_ALGORITHM_RS256, ], 'attachment_mode' => null, 'user_verification' => 'preferred', 'resident_key' => 'preferred', 'userless' => (bool) env('WEBAUTHN_USERLESS', false), ]; ``` -------------------------------- ### Direct controller invocation example Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Example of directly invoking the AuthenticateController's store method in tests or route closures. The response is expected to be an instance of LaravelWebauthn\Contracts\LoginSuccessResponse. ```php $response = app(AuthenticateController::class)->store($request); // $response instanceof LaravelWebauthn\Contracts\LoginSuccessResponse ``` -------------------------------- ### Define custom rate limiter for webauthn-login Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Define a custom rate limiter in the boot method of AppServiceProvider. This example sets a limit of 1000 requests per minute for the 'webauthn-login' limiter, overriding the default five requests per minute per email and IP. ```php use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ protected function boot(): void { RateLimiter::for('webauthn-login', function (Request $request) { return Limit::perMinute(1000); }); } } ``` -------------------------------- ### GET /webauthn/auth Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Displays the login page for WebAuthn authentication. This route is used to render the login form where users can initiate a WebAuthn login. ```APIDOC ## [GET] /webauthn/auth ### Description Displays the login page for WebAuthn authentication. ### Method GET ### Endpoint /webauthn/auth ### Parameters None ### Response #### Success Response (200) Returns the login page HTML. #### Response Example (HTML content) ``` -------------------------------- ### GET /webauthn/keys/create Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/endpoints.md Renders the registration page or returns public key creation options for registering a new key. ```APIDOC ## [GET] /webauthn/keys/create ### Description Renders the registration page or returns public key creation options for registering a new key. ### Method GET ### Endpoint /webauthn/keys/create ### Parameters None ### Response #### Success Response (200) - **publicKey** (object) - PublicKeyCredentialCreationOptions. #### Response Example { "publicKey": { "challenge": "...", "rp": {}, "user": {}, "pubKeyCredParams": [], "timeout": 60000 } } ### Error Handling - 422: Cannot register new key when `webauthn.enable=false` ``` -------------------------------- ### create(Request $request): RegisterViewResponse Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Generates a WebAuthn registration challenge for the authenticated user. Bound to GET /webauthn/keys/create and POST /webauthn/keys/options. ```APIDOC ## [GET] /webauthn/keys/create ### Description Generates a WebAuthn registration challenge for the authenticated user. Also bound to POST /webauthn/keys/options. ### Method GET ### Endpoint /webauthn/keys/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **RegisterViewResponse** (LaravelWebauthn\Contracts\RegisterViewResponse) - Contains the public key for registration. #### Response Example None ``` -------------------------------- ### Customizing the authentication pipeline Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Example from the README showing how to customize the Webauthn authentication pipeline using Webauthn::authenticateThrough. It conditionally includes EnsureLoginIsNotThrottled based on the login limiter configuration. ```php use LaravelWebauthn\Actions\AttemptToAuthenticate; use LaravelWebauthn\Actions\EnsureLoginIsNotThrottled; use LaravelWebauthn\Actions\PrepareAuthenticatedSession; use LaravelWebauthn\Services\Webauthn; Webauthn::authenticateThrough(fn ($request) => array_filter([ config('webauthn.limiters.login') !== null ? null : EnsureLoginIsNotThrottled::class, AttemptToAuthenticate::class, PrepareAuthenticatedSession::class, ])); ``` -------------------------------- ### Custom authentication pipeline with CheckDeviceIp and AttemptToAuthenticate Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/actions.md Define a custom authentication pipeline by composing project-specific steps with package actions. The example adds CheckDeviceIp before AttemptToAuthenticate; see controllers.md for the default definition. ```php use LaravelWebauthn\Actions\AttemptToAuthenticate; use LaravelWebauthn\Services\Webauthn; use App\Actions\CheckDeviceIp; Webauthn::authenticateThrough(function ($request) { return [ CheckDeviceIp::class, AttemptToAuthenticate::class, ]; }); ``` -------------------------------- ### GET /webauthn/keys/create Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/endpoints.md Returns the registration view for adding a new WebAuthn key. This endpoint is only registered when the 'webauthn.views.register' configuration is non-null. ```APIDOC ## GET /webauthn/keys/create ### Description Returns the registration view for adding a new WebAuthn key. ### Method GET ### Endpoint /webauthn/keys/create ### Route Name webauthn.create ### Authentication auth: ### Response #### Success Response (200) Returns the registration view. ``` -------------------------------- ### AuthenticateController::create Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Handles the 2FA/login flow by showing the challenge page and validating a login assertion. Bound to both GET /webauthn/auth and POST /webauthn/auth/options. ```APIDOC ## [GET] /webauthn/auth ### Description Handles the 2FA/login flow by showing the challenge page and validating a login assertion. Bound to both GET /webauthn/auth and POST /webauthn/auth/options. ### Method GET ### Endpoint /webauthn/auth ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - `username` (string) - Optional - The username for login attempt. ### Request Example { "username": "john.doe" } ### Response #### Success Response (200) - `LoginViewResponse` - The public key challenge for authentication. #### Response Example { "publicKey": { "challenge": "base64url-encoded-challenge", "rp": { "name": "Laravel WebAuthn" }, "user": { "id": "base64url-encoded-user-id", "name": "john.doe", "displayName": "John Doe" }, "pubKeyCredParams": [ { "type": "public-key", "alg": -7 } ], "timeout": 60000, "challenge": "base64url-encoded-challenge" } } ``` -------------------------------- ### boot() method declaration Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Public method that runs configuration, routes, resources, and auth provider registration in order. ```php public function boot(): void ``` -------------------------------- ### prepareAttestation(User $user): PublicKeyCredentialCreationOptions Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Builds the registration challenge via the container-resolved CreationOptionsFactory, caches it, and dispatches WebauthnRegisterData. ```APIDOC ## prepareAttestation(User $user): PublicKeyCredentialCreationOptions ### Description Builds the registration challenge via the container-resolved `CreationOptionsFactory`, caches it, and dispatches `WebauthnRegisterData`. ### Method `public static function prepareAttestation(User $user): PublicKeyCredentialCreationOptions` ### Parameters - `$user` (User) - Required - The user registering a new key. ### Returns `LaravelWebauthn\Services\Webauthn\PublicKeyCredentialCreationOptions` — `JsonSerializable` wrapper around creation options. ``` -------------------------------- ### Run database migrations Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Run the database migrations for the package. ```sh php artisan migrate ``` -------------------------------- ### GET /webauthn/auth Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/endpoints.md Returns the authentication view for WebAuthn login. This endpoint is only registered when the 'webauthn.views.authenticate' configuration is non-null. ```APIDOC ## GET /webauthn/auth ### Description Returns the authentication view for WebAuthn login. ### Method GET ### Endpoint /webauthn/auth ### Route Name webauthn.login ### Authentication Guard middleware (no login required) ### Response #### Success Response (200) Returns the authentication view. ``` -------------------------------- ### Publish configuration and resources Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Publish the package configuration and resources using the vendor:publish command. ```sh php artisan vendor:publish --provider="LaravelWebauthn\WebauthnServiceProvider" ``` -------------------------------- ### Prepare and validate a login with Webauthn facade Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Shows the basic login flow: prepare the assertion challenge for the browser, then validate the signed assertion. On success, call Webauthn::login() to mark 2FA done; on failure, call Webauthn::logout(). The validateAssertion call throws ResponseMismatchException if the response is not an AuthenticatorAssertionResponse. ```php use LaravelWebauthn\Facades\Webauthn; // 1. Serve the login challenge to the browser $publicKey = Webauthn::prepareAssertion($user); // JsonSerializable wrapper return response()->json($publicKey); // 2. Validate the signed assertion returned by the browser try { $ok = Webauthn::validateAssertion($user, [ 'id' => '...', 'rawId' => '...', 'type' => 'public-key', 'response' => [ 'authenticatorData' => '...', 'clientDataJSON' => '...', 'signature' => '...', 'userHandle' => '...', ], ]); } catch (\LaravelWebauthn\Exceptions\ResponseMismatchException $e) { // response was not an AuthenticatorAssertionResponse } if ($ok) { Webauthn::login($user); // mark 2FA done in session } else { Webauthn::logout(); } ``` -------------------------------- ### prepareAssertion(?User $user): PublicKeyCredentialRequestOptions Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Builds the login challenge via the container-resolved RequestOptionsFactory, caches it, and dispatches WebauthnLoginData with $publicKey->data. ```APIDOC ## prepareAssertion(?User $user): PublicKeyCredentialRequestOptions ### Description Builds the login challenge via the container-resolved `RequestOptionsFactory`, caches it, and dispatches `WebauthnLoginData` with `$publicKey->data` (the underlying `Webauthn\PublicKeyCredentialRequestOptions`). ### Method `public static function prepareAssertion(?User $user): PublicKeyCredentialRequestOptions` ### Parameters - `$user` (?User) - Required - The user to authenticate; `null` for userless/typless login. ### Returns `LaravelWebauthn\Services\Webauthn\PublicKeyCredentialRequestOptions` — a `JsonSerializable` wrapper around the request options (the value to send to the browser). ``` -------------------------------- ### Register a new WebAuthn key with JavaScript and Axios Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Loads the webauthn.js library and runs the browser registration, sending the signed data to the webauthn.store route with a name field. The publicKey is passed from the server via $publicKey, and the name from $name. The axios.post call sends the data to the route('webauthn.store') endpoint. ```html ... ``` -------------------------------- ### POST /webauthn/keys/options Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Retrieves the publicKeys and challenge required to initiate a WebAuthn registration. This endpoint is called before performing the registration ceremony. ```APIDOC ## [POST] /webauthn/keys/options ### Description Get the publicKeys and challenge to initiate a WebAuthn registration. ### Method POST ### Endpoint /webauthn/keys/options ### Parameters None ### Response #### Success Response (200) Returns the publicKeys and challenge. #### Response Example { "publicKeys": "...", "challenge": "..." } ``` -------------------------------- ### Catching WrongUserHandleException during attestation validation Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/errors.md Example of catching WrongUserHandleException when calling Webauthn::validateAttestation(). Occurs when the credential's userHandle does not belong to the user. ```php use LaravelWebauthn\Exceptions\WrongUserHandleException; try { $key = Webauthn::validateAttestation($user, $credentials, 'Key'); } catch (WrongUserHandleException $e) { // credential's userHandle does not belong to $user } ``` -------------------------------- ### Uuid cast class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-key-model.md Eloquent cast that returns a Uuid object on get if valid, otherwise null, and casts to string on set. ```php /** @implements CastsAttributes */ class Uuid implements CastsAttributes { #[ Override] public function get($model, string $key, $value, array $attributes): ?AbstractUid; #[ Override] public function set($model, string $key, mixed $value, array $attributes): ?string; } ``` -------------------------------- ### configureRoutes() method declaration Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Private method that registers package routes with namespace, domain, and prefix from configuration. ```php private function configureRoutes(): void ``` -------------------------------- ### TrustPath cast class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-key-model.md Eloquent cast that deserializes JSON into TrustPath on get and encodes to JSON on set. Throws JsonException on invalid values. ```php /** @implements CastsAttributes */ class TrustPath implements CastsAttributes { #[ Override] public function get($model, string $key, $value, array $attributes): ?TrustPathLib; #[ Override] public function set($model, string $key, mixed $value, array $attributes): ?string; } ``` -------------------------------- ### POST /webauthn/auth/options Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Retrieves the publicKey and challenge required to initiate a WebAuthn login. This endpoint is called before performing the WebAuthn authentication ceremony. ```APIDOC ## [POST] /webauthn/auth/options ### Description Get the publicKey and challenge to initiate a WebAuthn login. ### Method POST ### Endpoint /webauthn/auth/options ### Parameters None ### Response #### Success Response (200) Returns the publicKey and challenge. #### Response Example { "publicKey": "...", "challenge": "..." } ``` -------------------------------- ### Container bindings for webauthn.log and StatefulGuard Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Binds the webauthn.log channel and the StatefulGuard to the container using configuration values. ```php $this->app->bind('webauthn.log', fn ($app) => $app['log']->channel(config('webauthn.log', config('logging.default')))); $this->app->bind(StatefulGuard::class, fn () => Auth::guard(config('webauthn.guard', null))); ``` -------------------------------- ### Catching ResponseMismatchException during login validation Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/errors.md Example of catching ResponseMismatchException when calling Webauthn::validateAssertion(). Treat as failed login when the browser sends the wrong response shape. ```php use LaravelWebauthn\Exceptions\ResponseMismatchException; try { Webauthn::validateAssertion($user, $credentials); } catch (ResponseMismatchException $e) { // browser sent the wrong response shape — treat as failed login } ``` -------------------------------- ### WebauthnLoginAttemptRequest validation rules Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/http-requests.md Validates the login page / options request (GET webauthn.login, POST webauthn.auth.options). The username field is optional and must be a string. ```php class WebauthnLoginAttemptRequest extends FormRequest { public function rules(): array { return [ Webauthn::username() => 'sometimes|string', ]; } } ``` -------------------------------- ### Register a new key programmatically with Webauthn facade Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Prepares an attestation challenge for the browser, then validates the signed credential returned by the browser. The validateAttestation call takes the credentials array and a key name (e.g., 'My YubiKey'). ```php use LaravelWebauthn\Facades\Webauthn; $options = Webauthn::prepareAttestation($user); // challenge for browser // ... browser returns signed credential ... $key = Webauthn::validateAttestation($user, $credentials, 'My YubiKey'); ``` -------------------------------- ### redirects(string $redirect, ?string $default = null): ?string Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Reads config('webauthn.redirects.<$redirect>'); falls back to $default, then to '/home'. ```APIDOC ## redirects(string $redirect, ?string $default = null): ?string ### Description Reads `config('webauthn.redirects.<$redirect>')`; falls back to `$default`, then to `'/home'`. ### Method `public static function redirects(string $redirect, ?string $default = null): ?string` ### Parameters - `$redirect` (string) - Required - Config key under `webauthn.redirects` (e.g. `login`, `register`, `key-confirmation`). - `$default` (?string) - Optional - Fallback target URL. ### Returns `?string` — the redirect path. ``` -------------------------------- ### Base64 cast class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-key-model.md Eloquent cast that decodes base64url to raw bytes on get and encodes to base64url on set. Implements CastsAttributes with string types. ```php /** @implements CastsAttributes */ class Base64 implements CastsAttributes { #[\\Override] public function get($model, string $key, $value, array $attributes): ?string; #[ Override] public function set($model, string $key, mixed $value, array $attributes): ?string; } ``` -------------------------------- ### Define custom authentication pipeline with Webauthn::authenticateThrough Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Use this in the boot method of your FortifyServiceProvider to customize the login pipeline. The closure returns an array of classes, each with an __invoke method. The default pipeline includes EnsureLoginIsNotThrottled, AttemptToAuthenticate, and PrepareAuthenticatedSession, with conditional throttling based on the webauthn.limiters.login config. ```php use LaravelWebauthn\Actions\AttemptToAuthenticate; use LaravelWebauthn\Actions\EnsureLoginIsNotThrottled; use LaravelWebauthn\Actions\PrepareAuthenticatedSession; use LaravelWebauthn\Services\Webauthn; use Illuminate\Http\Request; Webauthn::authenticateThrough(fn (Request $request) => array_filter([ config('webauthn.limiters.login') !== null ? null : EnsureLoginIsNotThrottled::class, AttemptToAuthenticate::class, PrepareAuthenticatedSession::class, ])); ``` -------------------------------- ### GET /webauthn/auth Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/endpoints.md Renders the login page or returns public key request options for authentication. Accepts an optional username parameter and returns a view or JSON response. ```APIDOC ## [GET] /webauthn/auth ### Description Renders the login page or returns public key request options for authentication. Accepts an optional username parameter and returns a view or JSON response. ### Method GET ### Endpoint /webauthn/auth ### Parameters #### Query Parameters - **username** (string) - Optional - The username to use for authentication (defaults to `email`). ### Response #### Success Response (200) - **publicKey** (object) - PublicKeyCredentialRequestOptions containing challenge, rpId, allowCredentials, userVerification, timeout. #### Response Example { "publicKey": { "challenge": "...", "rpId": "...", "allowCredentials": [], "userVerification": "...", "timeout": 60000 } } ### Error Handling - 422: ValidationException (throttled or unknown user) - 429: Throttled when limiter configured ``` -------------------------------- ### register() method declaration with Override attribute Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Public method that merges config, binds package and PSR interfaces, and registers container bindings. ```php #[\Override] public function register(): void ``` -------------------------------- ### WebAuthn authentication sign flow with JavaScript Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Loads the webauthn.js library and runs the sign process. The publicKey is passed from the server, and on success the signed data is posted to the 'webauthn.auth' route. The response may contain a callback URL for redirection. ```html ... ``` -------------------------------- ### POST webauthn.store Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Submits the signed data from the WebAuthn browser registration to store the new key. The request must include a 'name' field for the key name. The response is either a redirect or a JSON response with a callback. ```APIDOC ## [POST] webauthn.store ### Description Submits the signed data from the WebAuthn browser registration to store the new key. The request must include a 'name' field for the key name. The response is either a redirect or a JSON response with a callback. ### Method POST ### Endpoint webauthn.store ### Parameters #### Request Body - **name** (string) - Required - The name of the WebAuthn key - **data** (object) - Required - The signed data from the WebAuthn browser registration ### Request Example ```json { "name": "My Key", "data": {} } ``` ### Response #### Success Response (200) - **redirect** (string) - Redirect response (plain HTTP call) - **result** (object) - JSON serialized WebAuthn key value (JSON response) - **callback** (string) - Target URL from webauthn.redirects.register configuration (JSON response) #### Response Example ```json { "result": {}, "callback": "https://example.com/redirect" } ``` ``` -------------------------------- ### CreationOptionsFactory final class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Builds registration challenges. Constructor reads webauthn.attestation_conveyance (default 'none') and passes request, cache, and config to parent. Additional dependencies include RP entity, authenticator selection criteria, algorithm manager, and credential repository. ```php final class CreationOptionsFactory extends OptionsFactory { protected string $attestationConveyance; public function __construct( Request $request, Cache $cache, Config $config, protected PublicKeyCredentialRpEntity $publicKeyCredentialRpEntity, protected AuthenticatorSelectionCriteria $authenticatorSelectionCriteria, protected CoseAlgorithmManager $algorithmManager, protected CredentialRepository $repository ) { parent::__construct($request, $cache, $config); $this->attestationConveyance = $config->get('webauthn.attestation_conveyance', 'none'); } } ``` -------------------------------- ### Publish only the config file Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Publishes only the configuration file (config/webauthn.php) to your application's config directory. Use the --tag=webauthn-config flag to target this specific group. ```php php artisan vendor:publish --tag=webauthn-config ``` -------------------------------- ### Configure webauthn user provider in auth.php Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Update the users provider in config/auth.php to use the webauthn driver for passwordless authentication. ```php 'providers' => [ 'users' => [ 'driver' => 'webauthn', 'model' => App\Models\User::class, ], ], ``` -------------------------------- ### Configure webauthn.limiters.login to use custom rate limiter Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Set the 'login' key in the 'limiters' configuration to the name of your custom rate limiter ('webauthn-login') to apply it to Webauthn login attempts. ```php 'limiters' => [ 'login' => 'webauthn-login', ], ``` -------------------------------- ### Customization hooks Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Provides methods to customize authentication, response handling, and route registration. Each method accepts a callback or closure. ```APIDOC ## Customization hooks ### Description Provides methods to customize authentication, response handling, and route registration. Each method accepts a callback or closure. ### Methods #### authenticateThrough(callable $callback): void ```php public static function authenticateThrough(callable $callback): void ``` - **$callback** (callable) - Required - A callable receiving `Illuminate\Http\Request` and returning the pipeline class array. #### authenticateUsing(callable $callback): void ```php public static function authenticateUsing(callable $callback): void ``` - **$callback** (callable) - Required - A callable receiving the request and returning a user or `null`. #### confirmKeyUsing(callable $callback): void ```php public static function confirmKeyUsing(callable $callback): void ``` - **$callback** (callable) - Required - A callable receiving the credential params array and returning `bool`. #### destroyViewResponseUsing(\Closure|string $callback): void ```php public static function destroyViewResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### updateViewResponseUsing(\Closure|string $callback): void ```php public static function updateViewResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### loginSuccessResponseUsing(\Closure|string $callback): void ```php public static function loginSuccessResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### loginViewResponseUsing(\Closure|string $callback): void ```php public static function loginViewResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### registerSuccessResponseUsing(\Closure|string $callback): void ```php public static function registerSuccessResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### registerViewResponseUsing(\Closure|string $callback): void ```php public static function registerViewResponseUsing(\Closure|string $callback): void ``` - **$callback** (\Closure|string) - Required - A class name or closure registered as a singleton replacement for the `\LaravelWebauthn\Contracts\*` response contract. #### ignoreRoutes(): void ```php public static function ignoreRoutes(): void ``` - No parameters. Sets `$registersRoutes = false` to prevent route registration. ### Notes - `*ResponseUsing` methods call `app()->singleton(::class, $callback)`. ``` -------------------------------- ### Facade login method signature Source: https://github.com/asbiin/laravel-webauthn/blob/main/docs/migration-v2-to-v3.md The login method now accepts a $user parameter of type Authenticatable. ```php login(\Illuminate\Contracts\Auth\Authenticatable $user): void ``` -------------------------------- ### LoginRateLimiter throttleKey method Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/middleware-rate-limiter.md Protected method that builds the throttle key from username and IP. ```php protected function throttleKey(Request $request): string { return Str::lower($request->input(Webauthn::username())).'|'.$request->ip(); } ``` -------------------------------- ### Custom Rate Limiter Configuration Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/middleware-rate-limiter.md Shows how to configure a custom rate limiter for WebAuthn login routes, bypassing the built-in limiter. ```APIDOC ## Custom Rate Limiter Configuration ### Description Shows how to configure a custom rate limiter for WebAuthn login routes, bypassing the built-in limiter. ### Usage ```php use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Support\Facades\RateLimiter; RateLimiter::for('webauthn-login', fn ($request) => Limit::perMinute(1000)); // config/webauthn.php 'limiters' => ['login' => 'webauthn-login'], ``` ### Notes When configured, the routes use Laravel's `throttle:` middleware and `EnsureLoginIsNotThrottled` is dropped from the default pipeline. ``` -------------------------------- ### __invoke(User $user) method signature Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Builds PublicKeyCredentialCreationOptions for registration. Uses user entity from Webauthn::username() attribute, random challenge, enabled algorithms, selection criteria, attestation conveyance, excluded credentials from CredentialRepository::getRegisteredKeys(), and timeout. Caches result under cacheKey($user) for $timeoutCache seconds. ```php public function __invoke(User $user): PublicKeyCredentialCreationOptions ``` -------------------------------- ### canRegister(User $user): bool Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Checks if WebAuthn is enabled, allowing registration. The user parameter is unused. ```APIDOC ## canRegister(User $user): bool ### Description Checks if WebAuthn is enabled, allowing registration. The user parameter is unused. ### Method Static method ### Signature ```php public static function canRegister(User $user): bool ``` ### Parameters - **$user** (User) - Required - The user (unused). ### Returns - **bool** - `webauthnEnabled()`. ``` -------------------------------- ### __invoke method signature Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Builds PublicKeyCredentialRequestOptions with challenge, rpId, allowed credentials, user verification, and timeout. When $user is null, allowCredentials is empty and challenge is cached under anonymous key. ```php public function __invoke(?User $user): PublicKeyCredentialRequestOptions ``` -------------------------------- ### forceAuthenticate(): void — deprecated Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Calls static::login(null). Deprecated, use login() instead. ```APIDOC ## forceAuthenticate(): void — deprecated ### Description Calls `static::login(null)`. Deprecated, use `login()` instead. ### Method `public static function forceAuthenticate(): void` ### Parameters No parameters. ### Returns `void` ``` -------------------------------- ### LoginRateLimiter availableIn method Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/middleware-rate-limiter.md Returns seconds until the lock expires. ```php public function availableIn(Request $request): int ``` -------------------------------- ### Abstract OptionsFactory class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Base class for building WebAuthn options. Constructor reads webauthn.challenge_length (default 32) and webauthn.timeout (milliseconds). When timeout is set, $timeoutCache equals timeout/1000 seconds; otherwise it uses getDefaultTimeoutCache() based on webauthn.user_verification. ```php abstract class OptionsFactory extends CredentialValidator { protected int $challengeLength; protected ?int $timeout = null; protected ?int $timeoutCache; public function __construct( Request $request, Cache $cache, Config $config ); } ``` -------------------------------- ### JSON response after successful registration Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Shows the structure of the JSON response returned when the registration is successful and the request expects JSON. Contains the serialized webauthn key value and the callback URL from the webauthn.redirects.register configuration. ```javascript { result: json serialized webauthn key value, callback: `webauthn.redirects.register` target url, } ``` -------------------------------- ### Constructor Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-auth-provider.md Creates a new EloquentWebAuthnProvider instance. Reads the webauthn.fallback configuration and passes the hasher and model to the parent Eloquent user provider. ```APIDOC ## Constructor ### Description Creates a new EloquentWebAuthnProvider instance. Reads the webauthn.fallback configuration and passes the hasher and model to the parent Eloquent user provider. ### Method Constructor ### Signature ```php public function __construct(Config $config, Hasher $hasher, string $model) ``` ### Parameters - **$config** (Illuminate\Contracts\Config\Repository) - Required - Reads `webauthn.fallback` (default `true`). - **$hasher** (Illuminate\Contracts\Hashing\Hasher) - Required - Passed to the parent Eloquent provider. - **$model** (string) - Required - The user model class (`$config['model']` from `config/auth.php`). ``` -------------------------------- ### Usage of WebauthnMiddleware in routes Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/middleware-rate-limiter.md Apply the middleware to routes, optionally with a guard parameter. ```php use LaravelWebauthn\Http\Middleware\WebauthnMiddleware; Route::get('/home', fn () => view('home')) ->middleware(WebauthnMiddleware::class); // with a guard parameter Route::get('/admin', ...)->middleware([WebauthnMiddleware::class.':admin']); ``` -------------------------------- ### webauthnEnabled(): bool Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Returns whether the WebAuthn master switch is enabled. Reads from configuration with a default of true. ```APIDOC ## webauthnEnabled(): bool ### Description Returns whether the WebAuthn master switch is enabled. Reads from configuration with a default of true. ### Method Static method ### Signature ```php public static function webauthnEnabled(): bool ``` ### Returns - **bool** - Cast of `config('webauthn.enable', true)`. ``` -------------------------------- ### Produce publicKey payload and cache challenge using CreationOptionsFactory Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Uses the CreationOptionsFactory to generate the publicKey payload for the browser and returns it as JSON. The factory is resolved from the container and called with the user, and the response uses jsonSerialize() to produce the publicKey object. ```php use LaravelWebauthn\Services\Webauthn\CreationOptionsFactory; $publicKey = app(CreationOptionsFactory::class)($user); return response()->json($publicKey); // jsonSerialize() → publicKey object ``` -------------------------------- ### login(?User $user): void Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Stores the webauthn-auth flag in the session under sessionName() and, when $user is not null, dispatches LaravelWebauthn\Events\WebauthnLogin. ```APIDOC ## login(?User $user): void ### Description Stores the webauthn-auth flag in the session under `sessionName()` and, when `$user` is not `null`, dispatches `LaravelWebauthn\Events\WebauthnLogin`. ### Method `public static function login(?User $user): void` ### Parameters - `$user` (?User) - Required - The authenticated user, or `null` to only set the session flag. ### Throws - `LaravelWebauthn\Exceptions\WrongUserHandleException` indirectly if the stored `CredentialRecord`'s user handle mismatches during later persistence. ``` -------------------------------- ### JsonWrapper::jsonSerialize Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Returns the serialized options as an array for response()->json(). ```APIDOC ## JsonWrapper::jsonSerialize ### Description Returns the serialized options as an array for response()->json(). ### Method jsonSerialize ### Parameters None. ### Response #### Success Response (200) - **array** (array) - The serialized options as an array. #### Response Example { "challenge": "base64url-encoded-challenge", "rpId": "example.com", "allowCredentials": [], "userVerification": "preferred", "timeout": 60000 } ``` -------------------------------- ### Final wrapper classes for PublicKeyCredentialRequestOptions and PublicKeyCredentialCreationOptions Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Defines two final wrapper classes that extend JsonWrapper and use a static create() method to resolve the wrapper from the container, storing the web-auth base object in $data. Both implement JsonSerializable, and the wrapped $data is exposed for events and view responses. ```php /** @extends JsonWrapper */ final class PublicKeyCredentialRequestOptions extends JsonWrapper { public static function create(PublicKeyCredentialRequestOptionsBase $data): self { return app(self::class, ['data' => $data]); } } /** @extends JsonWrapper */ final class PublicKeyCredentialCreationOptions extends JsonWrapper { public static function create(PublicKeyCredentialCreationOptionsBase $data): self { return app(self::class, ['data' => $data]); } } ``` -------------------------------- ### sessionName(): string Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/webauthn-service.md Returns the session name used for the webauthn-auth flag. Falls back to legacy configuration and defaults to 'webauthn_auth'. ```APIDOC ## sessionName(): string ### Description Returns the session name used for the webauthn-auth flag. Falls back to legacy configuration and defaults to 'webauthn_auth'. ### Method Static method ### Signature ```php public static function sessionName(): string ``` ### Returns - **string** - `config('webauthn.session_name')`, falling back to legacy `webauthn.sessionName`, default `'webauthn_auth'`. ``` -------------------------------- ### getChallenge() protected method Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/options-factories.md Generates a random challenge string using random_bytes with the configured challenge length. Throws \Exception if no entropy source is available. ```php protected function getChallenge(): string { return \random_bytes($this->challengeLength); } ``` -------------------------------- ### passwordLessWebauthn() method declaration Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/service-provider.md Private method that registers the webauthn auth provider driver. ```php private function passwordLessWebauthn(): void ``` -------------------------------- ### ConfirmableKeyController::__construct Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Constructor for the ConfirmableKeyController. Injects the stateful guard used for authentication. ```APIDOC ## ConfirmableKeyController::__construct ### Description Constructor for the ConfirmableKeyController. Injects the stateful guard used for authentication. ### Method Constructor ### Parameters - `$guard` (Illuminate\Contracts\Auth\StatefulGuard) - Required - Container-bound to `Auth::guard(config('webauthn.guard'))`. ### Request Example ```php public function __construct(protected StatefulGuard $guard) {} ``` ``` -------------------------------- ### PrepareCreationData action class Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/actions.md Invokable action that throws ValidationException with webauthn::errors.cannot_register_new_key and dispatches WebauthnRegisterFailed with $e = null when registration is not allowed, otherwise forwards to Webauthn::prepareAttestation($user). ```php class PrepareCreationData { public function __invoke(User $user): PublicKeyCredentialCreationOptions; } ``` -------------------------------- ### POST /webauthn/keys/options Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/endpoints.md Generates a registration challenge for a new WebAuthn key. ```APIDOC ## [POST] /webauthn/keys/options ### Description Generates a registration challenge for a new WebAuthn key. ### Method POST ### Endpoint /webauthn/keys/options ### Parameters None ### Response #### Success Response (200) - **publicKey** (object) - PublicKeyCredentialCreationOptions. #### Response Example { "publicKey": { "challenge": "...", "rp": {}, "user": {}, "pubKeyCredParams": [], "timeout": 60000 } } ``` -------------------------------- ### ConfirmableKeyController constructor Source: https://github.com/asbiin/laravel-webauthn/blob/main/_autodocs/api-reference/controllers.md Constructor for ConfirmableKeyController that injects a StatefulGuard instance. The guard is container-bound to Auth::guard(config('webauthn.guard')). ```php public function __construct(protected StatefulGuard $guard) {} ``` -------------------------------- ### Set redirects array in config Source: https://github.com/asbiin/laravel-webauthn/blob/main/docs/migration-v1-to-v2.md Define URLs to redirect to after successful login or register key. Redirects are not used for application/json requests. ```php 'redirects' => [ 'login' => null, 'register' => null, ]; ``` -------------------------------- ### v1 & v2: Send data to webauthn.auth route Source: https://github.com/asbiin/laravel-webauthn/blob/main/docs/migration-v2-to-v3.md In v1 and v2, the webauthn signature data was sent in a 'data' parameter to the 'webauthn.auth' route after a login validation. ```javascript webauthn.sign( publicKey, function (data) { /* Send 'data' to validate login */ axios.post(route('webauthn.auth'), { data: JSON.stringify(data), remember: this.remember ? 'on' : '' }).then( /* ... */ ); } ); ``` -------------------------------- ### POST /webauthn/confirm-key Source: https://github.com/asbiin/laravel-webauthn/blob/main/README.md Tests a WebAuthn authentication without requiring a login. This endpoint is used to verify a key's validity. ```APIDOC ## [POST] /webauthn/confirm-key ### Description Post data to test a WebAuthn authentication without login. ### Method POST ### Endpoint /webauthn/confirm-key ### Parameters #### Request Body - (object) - Required - The WebAuthn authentication data. ### Response #### Success Response (200) Indicates successful authentication test. #### Response Example { "success": true } ```