Skip to content

Two-Factor Authentication

View raw .md

The TOTP second factor: enrolling a user, confirming the code, recovery codes and the challenge that finishes a sign-in.

On this page

Quick Reference#

Enable the two-factor-authentication feature, then use these endpoints under {prefix}, the route_prefix config value (api/v1 by default).

Endpoint Auth Does
POST {prefix}/two-factor-authentication auth:sanctum Generates a secret and recovery codes and returns the QR code. Not active until confirmed.
POST {prefix}/two-factor-authentication/confirm auth:sanctum Confirms the first TOTP code and activates 2FA.
DELETE {prefix}/two-factor-authentication auth:sanctum Turns 2FA off.
POST {prefix}/two-factor-recovery-codes/show auth:sanctum Lists the recovery codes; a POST because it carries the password.
POST {prefix}/two-factor-recovery-codes auth:sanctum Replaces every recovery code with a new set.
POST {prefix}/auth/two-factor-challenge the two_factor_token Exchanges the token and a TOTP or recovery code for a Sanctum token.

Introduction#

Magic Starter provides TOTP-based (Time-based One-Time Password) two-factor authentication. The feature is disabled by default and must be explicitly opted in via the feature flag.

When 2FA is enabled, the login flow becomes a two-step process: the normal credential check returns a short-lived two_factor_token instead of a Sanctum token, and the client then exchanges that token (plus a TOTP code or recovery code) for the actual Sanctum bearer token.

The TOTP implementation uses pragmarx/google2fa under the hood. QR codes are rendered as inline SVG using bacon/bacon-qr-code, so no external image service is involved.

Enabling the feature:

php
// config/magic-starter.php
'features' => [
    \AnilcanCakir\MagicStarter\Features::twoFactorAuthentication(),
],

All 2FA management endpoints (POST/DELETE two-factor-authentication, POST two-factor-recovery-codes/*) require auth:sanctum middleware. The challenge endpoint (POST auth/two-factor-challenge) is public but rate-limited.


Enable 2FA#

Initiates 2FA setup for the authenticated user. Generates a TOTP secret, a set of recovery codes, and returns a QR code SVG ready to display to the user. 2FA is not yet active until confirmed; see Confirm 2FA.

Endpoint

text
POST /api/v1/two-factor-authentication

Headers

Header Value
Authorization Bearer {token}
Accept application/json

Request body

None required.

Response 200 OK

json
{
  "data": {
    "secret": "BASE32ENCODEDSECRET",
    "qr_url": "otpauth://totp/AppName:[email protected]?secret=BASE32ENCODEDSECRET&issuer=AppName",
    "qr_svg": "<svg xmlns=\"http://www.w3.org/2000/svg\" ...>...</svg>",
    "recovery_codes": [
      "abc12-def34",
      "ghi56-jkl78"
    ]
  },
  "message": "Two-factor authentication enabled. Please confirm with your authenticator app."
}
Field Description
secret The base32-encoded TOTP secret. Store securely and show it once.
qr_url The otpauth:// URI. Can be used to generate a custom QR code client-side.
qr_svg Inline SVG QR code (192 px). Render directly in the UI without any dependencies.
recovery_codes One-time-use backup codes. Show to the user and prompt them to save securely.

Confirm 2FA#

Activates 2FA by verifying the first TOTP code from the authenticator app. Until this endpoint is called successfully, hasEnabledTwoFactorAuthentication() returns false and the 2FA challenge is not enforced during login.

Endpoint

text
POST /api/v1/two-factor-authentication/confirm

Headers

Header Value
Authorization Bearer {token}
Accept application/json
Content-Type application/json

Request body

Field Type Required Description
code string yes 6-digit TOTP code from the authenticator app.
json
{
  "code": "123456"
}

Response 200 OK

json
{
  "data": null,
  "message": "Two-factor authentication confirmed successfully."
}

Disable 2FA#

Disables two-factor authentication for the authenticated user. Clears the stored secret, recovery codes, and confirmation timestamp.

Endpoint

text
DELETE /api/v1/two-factor-authentication

Headers

Header Value
Authorization Bearer {token}
Accept application/json

Request body

None required.

Response 200 OK

json
{
  "data": null,
  "message": "Two-factor authentication has been disabled."
}

Recovery Codes#

Recovery codes are one-time-use backup codes generated when 2FA is enabled. Each code can only be used once: after use it is replaced with a newly generated random code in the stored set.

Both recovery code endpoints require password confirmation (sudo mode) in the request body to prevent unauthorized access.

View Recovery Codes#

Returns the current list of unused recovery codes.

Endpoint

text
POST /api/v1/two-factor-recovery-codes/show

Headers

Header Value
Authorization Bearer {token}
Accept application/json
Content-Type application/json

Request body

Field Type Required Description
password string yes The user's current password.
json
{
  "password": "current-password"
}

Response 200 OK

json
{
  "data": [
    "abc12-def34",
    "ghi56-jkl78"
  ],
  "message": "Recovery codes retrieved successfully."
}

Response 403 Forbidden, when 2FA is not enabled:

json
{
  "message": "Two-factor authentication is not enabled."
}

Regenerate Recovery Codes#

Generates a fresh set of recovery codes, invalidating all previous ones. Use this when recovery codes have been exhausted or potentially compromised.

Endpoint

text
POST /api/v1/two-factor-recovery-codes

Headers

Header Value
Authorization Bearer {token}
Accept application/json
Content-Type application/json

Request body

Field Type Required Description
password string yes The user's current password.
json
{
  "password": "current-password"
}

Response 200 OK

json
{
  "data": [
    "newcode1-abc12",
    "newcode2-def34"
  ],
  "message": "Recovery codes regenerated successfully."
}

2FA Challenge#

When a user with confirmed 2FA enabled logs in, the login endpoint returns a two_factor_token instead of a Sanctum bearer token. The client must exchange this token, together with either a TOTP code or a recovery code, for the actual session token.

The challenge token is a short-lived encrypted payload. Its TTL is controlled by magic-starter.two_factor.challenge_token_ttl (default: 5 minutes).

Endpoint

text
POST /api/v1/auth/two-factor-challenge

Headers

Header Value
Accept application/json
Content-Type application/json

Verify with TOTP Code#

Request body

Field Type Required Description
two_factor_token string yes The encrypted token returned by the login endpoint.
code string yes 6-digit TOTP code from the user's authenticator app.
json
{
  "two_factor_token": "eyJpdiI6Ij...",
  "code": "123456"
}

Verify with Recovery Code#

Request body

Field Type Required Description
two_factor_token string yes The encrypted token returned by the login endpoint.
recovery_code string yes One of the user's unused recovery codes.
json
{
  "two_factor_token": "eyJpdiI6Ij...",
  "recovery_code": "abc12-def34"
}

Response 200 OK, same shape as the normal login response:

json
{
  "data": {
    "token": "sanctum-bearer-token",
    "user": { "..." : "..." }
  }
}

Error responses

Scenario Field Message
Tampered or invalid token two_factor_token Invalid two-factor authentication token.
Expired token two_factor_token Two-factor authentication token has expired.
Invalid TOTP code code The provided two-factor authentication code was invalid.
Invalid recovery code recovery_code The provided two-factor authentication recovery code was invalid.

TwoFactorAuthenticatable Trait#

Add this trait to your User model to provide the 2FA capabilities the package relies on.

php
use AnilcanCakir\MagicStarter\Traits\TwoFactorAuthenticatable;

class User extends Authenticatable
{
    use TwoFactorAuthenticatable;
}

Database columns required (added by the package migration):

Column Type Description
two_factor_secret `text null`
two_factor_recovery_codes `text null`
two_factor_confirmed_at `timestamp null`

Public methods provided by the trait:

Method Return type Description
hasEnabledTwoFactorAuthentication() bool Returns true only when two_factor_confirmed_at is not null.
twoFactorSecret() string|null Decrypts and returns the raw base32 secret.
recoveryCodes() array<int,string> Decrypts and returns the current recovery code array.
twoFactorRecoveryCodesCount() int Returns the count of remaining recovery codes.
replaceRecoveryCode(string $code) void Replaces a consumed recovery code with a fresh random string.
twoFactorQrCodeUrl() string Returns the otpauth:// URI for QR code enrollment.
twoFactorQrCodeSvg() string Returns an inline SVG QR code (192 px) as a string.

Configuration#

All 2FA settings live under the two_factor key in config/magic-starter.php.

php
'two_factor' => [
    'company_name'         => env('APP_NAME', 'Laravel'),
    'recovery_codes_count' => 8,
    'geoip_db_path'        => null,
    'challenge_token_ttl'  => 5,
],
Key Default Description
company_name APP_NAME Issuer name shown in the authenticator app next to the account entry. Falls back to config('app.name').
recovery_codes_count 8 Number of recovery codes generated when 2FA is enabled or regenerated.
geoip_db_path null Absolute path to a MaxMind GeoIP2 .mmdb file. Only the sessions list reads it, to show the city and country of each session whose address resolves; the challenge itself does not use it. Set to null to disable geo-resolution.
challenge_token_ttl 5 Minutes before the two_factor_token issued at login expires. Users must complete the challenge within this window.

Gotchas#

Mistake Fix
Expecting 2FA to be enforced after enabling it The challenge applies only once the first code is confirmed at two-factor-authentication/confirm.
Calling enable twice before confirming The second call overwrites the unconfirmed secret and the recovery codes, so the first QR code stops working.
Sending the two_factor_token as a bearer token It is not a Sanctum token. Post it, with a code, to auth/two-factor-challenge.
Showing the recovery codes once and discarding the new set after a regeneration Regenerating invalidates every earlier code at once. Present the new set before the user leaves the screen.
Rotating APP_KEY without re-encrypting the 2FA columns The secret and recovery codes are stored encrypted, so every enrolled user would be locked out of the second factor.
Taking a long time to submit the challenge The two_factor_token expires after two_factor.challenge_token_ttl minutes (5 by default).
esc

Search index did not load.

No match for "".

Try a class like rounded-lg or a widget like WButton.