Authentication
The Sanctum token endpoints for signing in, registering, signing out, resetting a password, guest sessions, phone OTP and the two-factor challenge.
On this page
Quick Reference#
Every path sits under {prefix}, the route_prefix config value (api/v1 by default).
| Endpoint | Auth | Needs | Rate limit |
|---|---|---|---|
POST {prefix}/auth/login |
none | 5 a minute per IP and email | |
POST {prefix}/auth/register |
none | 3 a minute per IP | |
POST {prefix}/auth/logout |
auth:sanctum |
none | |
GET {prefix}/auth/user |
auth:sanctum |
none | |
POST {prefix}/auth/forgot-password |
none | 3 a minute per IP and email | |
POST {prefix}/auth/reset-password |
none | 3 a minute per IP and email | |
POST {prefix}/auth/guest |
none | guest-auth |
10 a minute per IP and device ID |
POST {prefix}/auth/guest/claim |
auth:sanctum |
guest-auth |
10 a minute per IP |
POST {prefix}/auth/otp/send |
none | phone-otp |
2 a minute per IP and phone |
POST {prefix}/auth/otp/verify |
none | phone-otp |
5 a minute per IP and phone |
POST {prefix}/auth/two-factor-challenge |
none | two-factor-authentication |
5 a minute per IP and challenge token |
PUT {prefix}/user/current-team |
auth:sanctum |
teams |
none |
A successful sign-in answers {"data": {"user": {...}, "token": "1|abc..."}}. Send the token on every later request as Authorization: Bearer {token}.
Introduction#
Magic Starter uses Laravel Sanctum for token-based API authentication. Every authenticated response returns a plain-text Bearer token that must be included in subsequent requests via the Authorization header:
Authorization: Bearer {token}
All authentication routes are registered under the configurable route prefix (config('magic-starter.route_prefix')). Throughout this document, {prefix} refers to that value. If no prefix is configured, routes are registered at the root.
The identity strategy is configurable. Magic Starter supports email-based, phone-based, or dual-identity login and registration. This is controlled by config('magic-starter.auth.email') and config('magic-starter.auth.phone'). When both are enabled, users may authenticate with either identifier.
Device information (IP address and user agent) is automatically stored on every issued token for session management purposes.
Login#
Authenticates a user by email or phone and password. When two-factor authentication is enabled for the user, returns a challenge token instead of the full auth response.
Endpoint: POST {prefix}/auth/login
Middleware: throttle:magic-starter-auth-login
Rate Limit: 5 requests per minute, keyed by IP + email.
Request Body#
The identity field varies based on the configured authentication strategy:
Email-only (default):
{
"email": "[email protected]",
"password": "secret123"
}
Phone-only:
{
"phone": "+905551234567",
"password": "secret123"
}
Dual-identity (email + phone enabled):
Provide either email or phone -- at least one is required.
{
"email": "[email protected]",
"password": "secret123"
}
| Field | Type | Rules |
|---|---|---|
email |
string | Required (or required_without:phone in dual mode). Valid email. |
phone |
string | Required (or required_without:email in dual mode). E.164 format. |
password |
string | Required. |
remember_me |
boolean | Optional. true, false, 1, 0, "1" or "0"; anything else answers 422. |
remember_me: true gives the token the remember_me_expiration_minutes lifetime instead of token_expiration_minutes; when that is null the token falls back to token_expiration_minutes. When both are null the token does not expire unless sanctum.expiration says so. See Configuration.
Success Response (200)#
{
"data": {
"user": {
"id": "9a8b7c6d-...",
"name": "John Doe",
"email": "[email protected]",
"phone": null,
"is_guest": false,
"email_verified_at": "2025-01-01T00:00:00.000000Z",
"locale": "en",
"timezone": "UTC",
"profile_photo_url": null,
"two_factor_enabled": false,
"current_team": { "..." },
"all_teams": [ "..." ],
"created_at": "2025-01-01T00:00:00.000000Z",
"updated_at": "2025-01-01T00:00:00.000000Z"
},
"token": "1|abc123..."
},
"message": "Login successful"
}
Two-Factor Challenge Response (200)#
When the user has 2FA enabled, the login endpoint returns a challenge token instead:
{
"two_factor": true,
"two_factor_token": "eyJpdiI6..."
}
The client must then call the Two-Factor Challenge endpoint with this token.
Error Response (401)#
{
"message": "Invalid credentials"
}
Registration#
Creates a new user account and returns an authenticated response with a Sanctum token.
Endpoint: POST {prefix}/auth/register
Middleware: throttle:magic-starter-auth-register
Rate Limit: 3 requests per minute, keyed by IP.
Request Body#
{
"name": "John Doe",
"email": "[email protected]",
"password": "Secret123",
"password_confirmation": "Secret123",
"locale": "en",
"timezone": "Europe/Istanbul",
"subscribe_newsletter": true
}
| Field | Type | Rules |
|---|---|---|
name |
string | Required. Max 255 characters. |
email |
string | Required (or required_without:phone in dual mode). Valid email. Unique in users table. |
phone |
string | Required (or required_without:email in dual mode). E.164 format. Unique in users table. |
password |
string | Required. Min 8 chars, must contain letters, numbers, and mixed case. Must be confirmed. |
password_confirmation |
string | Required. Must match password. |
locale |
string | Optional. Must be in config('magic-starter.supported_locales'). |
timezone |
string | Optional. Must be a valid IANA timezone identifier. |
subscribe_newsletter |
boolean | Optional. When true and the newsletter feature is enabled, creates a subscriber record. |
Success Response (201)#
{
"data": {
"user": { "..." },
"token": "1|abc123..."
},
"message": "Registration successful"
}
The user resource shape is the same as described in Login.
Validation Error Response (422)#
{
"message": "The email has already been taken.",
"errors": {
"email": ["The email has already been taken."]
}
}
Logout#
Revokes the current Sanctum access token. An account's other devices stay signed in.
A guest's sign-out ends the guest session for good: every token the guest holds is revoked and its device_id is released, as a claim does. A later POST auth/guest from the same device opens a NEW guest row (201), and no token the guest held can claim it. The row keeps is_guest, so a job pruning abandoned guests can still reclaim it.
Endpoint: POST {prefix}/auth/logout
Middleware: auth:sanctum
Request Body#
No body required. The token is identified from the Authorization header.
Success Response (200)#
{
"data": null,
"message": "Logged out successfully"
}
Current User#
Returns the currently authenticated user.
Endpoint: GET {prefix}/auth/user
Middleware: auth:sanctum
Success Response (200)#
{
"data": {
"id": "9a8b7c6d-...",
"name": "John Doe",
"email": "[email protected]",
"phone": null,
"is_guest": false,
"email_verified_at": "2025-01-01T00:00:00.000000Z",
"locale": "en",
"timezone": "UTC",
"profile_photo_url": null,
"two_factor_enabled": false,
"current_team": { "..." },
"all_teams": [ "..." ],
"created_at": "2025-01-01T00:00:00.000000Z",
"updated_at": "2025-01-01T00:00:00.000000Z"
}
}
Social Login#
Google, Apple, GitHub and Microsoft sign-in, plus connecting and disconnecting providers from the profile, is documented in Social Login. It is available when Features::socialLogin() is on, and it needs HasSocialAccounts and NormalizesEmail on the user model.
Password Reset#
A two-step flow: first request a reset link, then submit the new password with the token received via email.
Send Reset Link#
Sends a password reset email. Always returns 200 regardless of whether the email exists, to prevent user enumeration.
Endpoint: POST {prefix}/auth/forgot-password
Middleware: throttle:magic-starter-auth-password-reset
Rate Limit: 3 requests per minute, keyed by IP + email.
Request Body
{
"email": "[email protected]"
}
| Field | Type | Rules |
|---|---|---|
email |
string | Required. Email. |
Success Response (200)
{
"data": null,
"message": "If an account with that email exists, a password reset link has been sent."
}
Reset Password#
Resets the user's password using the token from the email.
Endpoint: POST {prefix}/auth/reset-password
Middleware: throttle:magic-starter-auth-password-reset
Rate Limit: 3 requests per minute, keyed by IP + email.
Request Body
{
"token": "a1b2c3d4...",
"email": "[email protected]",
"password": "NewSecret123",
"password_confirmation": "NewSecret123"
}
| Field | Type | Rules |
|---|---|---|
token |
string | Required. The reset token from the email. |
email |
string | Required. Email. |
password |
string | Required. Min 8 chars, letters, numbers, mixed case. Must be confirmed. |
password_confirmation |
string | Required. Must match password. |
Success Response (200)
{
"data": null,
"message": "Your password has been reset."
}
Error Response (422)
Returned when the token is invalid, expired, or the email does not match.
{
"data": null,
"message": "This password reset token is invalid."
}
Guest Authentication#
Creates or retrieves a guest user identified by a device ID, and issues a Sanctum token. Guest users have null email and null password.
Endpoint: POST {prefix}/auth/guest
Middleware: throttle:magic-starter-guest-auth
Rate Limit: 10 requests per minute, keyed by IP + device ID.
Request Body#
{
"device_id": "a1b2c3d4-e5f6-..."
}
| Field | Type | Rules |
|---|---|---|
device_id |
string | Required. Max 255 characters. |
Success Response (201 -- new guest, 200 -- returning guest)#
{
"data": {
"user": {
"id": "...",
"name": "Guest",
"email": null,
"phone": null,
"is_guest": true,
"..."
},
"token": "1|abc123..."
},
"message": "Guest session started"
}
When a returning guest authenticates (same device_id), all previous tokens are revoked before issuing a new one to prevent session buildup.
A device_id only ever matches a row that is still a guest. An account that was promoted out of a guest session, a guest that was claimed by the endpoint below, or a guest that signed out, releases the identifier, so a later call with that same device_id opens a NEW guest row (201) rather than returning the old one. Nothing reads device_id on a registered account, so releasing it costs that account nothing, and it is what stops an identifier that travels in a request body with no credential beside it from reopening somebody's promoted account.
Claim a Guest Session#
Moves a guest session into an account that already exists. This is the case conversion cannot serve: the person signs in to an account they already had, so the guest row and the account row are two different users and everything the guest accumulated is scoped to a user id nobody will authenticate as again.
The caller authenticates as the TARGET account and presents the guest session's own token in the body, so both halves are proved by possession.
Endpoint: POST {prefix}/auth/guest/claim
Middleware: auth:sanctum, throttle:magic-starter-guest-auth
Rate Limit: 10 requests per minute, keyed by IP (this payload carries no device ID).
Request Body
{
"guest_token": "3|xyz789..."
}
| Field | Type | Rules |
|---|---|---|
guest_token |
string | Required. The guest session's own plain-text Sanctum token. |
Success Response (200)
{
"data": {
"user": {
"id": "...",
"is_guest": false,
"..."
},
"claimed": true
}
}
claimed reports whether this call performed the transfer. A repeat of a claim that already succeeded answers 200 with claimed: false, because the first call deleted the guest's tokens and there is no live guest session left to claim. That keeps a client's retry safe without pretending a second transfer took place, and the same answer covers a token that has expired or aged past sanctum.expiration.
Refusal (422)
{
"message": "The selected guest token is invalid.",
"errors": {
"guest_token": ["The selected guest token is invalid."]
}
}
One refusal for four causes, deliberately: the token names something that cannot be authenticated, something that is not the configured user model, a user that is not a guest, or the caller themselves. Telling them apart would turn the endpoint into an oracle about other people's tokens.
What Moves
The whole transfer runs in one database transaction.
- The package moves the rows it owns. That is the guest's database notifications and support conversations, and nothing else (a conversation filed under a team the account does not belong to moves to the account's current team): notification settings carry a unique key per type and channel, so a guest's defaults would collide with choices the account has already made; a personal team is not moved because the target already owns one; newsletter subscriptions are keyed on an email address a guest never had.
AnilcanCakir\MagicStarter\Events\GuestClaimedis dispatched with both user models. This is the whole seam for your own data: reassign your tables from$event->guestto$event->targetin a listener.- The guest's tokens are deleted and its
device_idis released. The row keepsis_guest, so a job pruning abandoned guests can still reclaim it; with no token, no device ID, no email and no password, nothing can authenticate as it again.
use AnilcanCakir\MagicStarter\Events\GuestClaimed;
use Illuminate\Support\Facades\Event;
Event::listen(GuestClaimed::class, function (GuestClaimed $event): void {
Bookmark::query()
->where('user_id', $event->guest->getAuthIdentifier())
->update(['user_id' => $event->target->getAuthIdentifier()]);
});
Phone OTP#
A two-step phone-based authentication flow: send a 6-digit OTP code to a phone number, then verify the code to receive an auth token. The OTP is cached for 5 minutes.
Send OTP#
Sends a 6-digit OTP code to the provided phone number. The actual delivery mechanism is delegated to the SendsOtpCodes contract, which you must bind in your application.
Endpoint: POST {prefix}/auth/otp/send
Middleware: throttle:magic-starter-otp
Rate Limit: 2 requests per minute, keyed by IP + phone.
Request Body
{
"phone": "+905551234567"
}
| Field | Type | Rules |
|---|---|---|
phone |
string | Required. E.164 format. |
Success Response (200)
{
"message": "OTP sent successfully"
}
Verify OTP#
Verifies the OTP code and authenticates the user associated with the phone number. The verification logic is delegated to the VerifiesOtpCodes contract.
Endpoint: POST {prefix}/auth/otp/verify
Middleware: throttle:magic-starter-otp
Rate Limit: 5 requests per minute, keyed by IP + phone.
Request Body
{
"phone": "+905551234567",
"code": "123456"
}
| Field | Type | Rules |
|---|---|---|
phone |
string | Required. E.164 format. |
code |
string | Required. Exactly 6 characters. |
Success Response (200)
Same shape as the Login success response.
Error Response (401)
{
"message": "Invalid or expired OTP"
}
Error Response (404)
Returned when the OTP is valid but no user exists with the given phone number.
{
"message": "User not found"
}
Two-Factor Challenge#
Completes a two-factor authentication challenge after a successful login that returned "two_factor": true. Accepts either a TOTP code from an authenticator app or a recovery code.
Endpoint: POST {prefix}/auth/two-factor-challenge
Middleware: throttle:magic-starter-2fa-challenge
Rate Limit: 5 requests per minute, keyed by IP + two-factor token.
Request Body (TOTP code)#
{
"two_factor_token": "eyJpdiI6...",
"code": "123456"
}
Request Body (Recovery code)#
{
"two_factor_token": "eyJpdiI6...",
"recovery_code": "abcde-12345"
}
| Field | Type | Rules |
|---|---|---|
two_factor_token |
string | Required. The encrypted challenge token from the login response. |
code |
string | Nullable. The 6-digit TOTP code. |
recovery_code |
string | Nullable. A one-time recovery code. |
When recovery_code is provided, the code field is automatically nullified. Provide one or the other, not both.
The challenge token expires after the configured TTL (config('magic-starter.two_factor.challenge_token_ttl'), default: 5 minutes).
The challenge token also carries the remember_me the login sent, so the token this endpoint issues gets the same lifetime the login would have given it. A challenge token minted before this field existed counts as remember_me: false.
Success Response (200)#
Same shape as the Login success response.
Error Responses (422)#
Expired token:
{
"message": "The given data was invalid.",
"errors": {
"two_factor_token": ["Two-factor authentication token has expired."]
}
}
Invalid TOTP code:
{
"message": "The given data was invalid.",
"errors": {
"code": ["The provided two-factor authentication code was invalid."]
}
}
Invalid recovery code:
{
"message": "The given data was invalid.",
"errors": {
"recovery_code": ["The provided two-factor authentication recovery code was invalid."]
}
}
Switch Team#
Switches the authenticated user's current team. The user must be a member of the target team.
Endpoint: PUT {prefix}/user/current-team
Middleware: auth:sanctum
Request Body#
{
"team_id": "9a8b7c6d-..."
}
| Field | Type | Rules |
|---|---|---|
team_id |
string | Required. UUID. Must exist in the teams table. |
Authorization is enforced via the switchTo Gate -- the user must be permitted to switch to the given team.
Success Response (200)#
{
"data": {
"id": "...",
"name": "John Doe",
"email": "[email protected]",
"current_team": {
"id": "9a8b7c6d-...",
"name": "My Team",
"..."
},
"..."
},
"message": "Team switched successfully"
}
Error Response (403)#
{
"message": "You are not a member of this team."
}
Gotchas#
| Mistake | Fix |
|---|---|
Treating a 200 from login as signed in |
When the answer carries "two_factor": true it holds a two_factor_token, not a Sanctum token. Post it to the two-factor challenge. |
| Letting the reset link open the backend host | Set MAGIC_STARTER_FRONTEND_URL; the link is built from frontend_url. |
Sending the guest token as the bearer on auth/guest/claim |
Authenticate as the target account and put the guest session's token in the body. |
Queueing a listener for GuestClaimed |
The event runs inside the claim's transaction. Keep the listener synchronous and let it throw to undo the claim. |
Expecting auth.phone to switch on OTP |
It only lets a phone number sign in. The OTP endpoints need the phone-otp feature as well. |
| Retrying login in a loop | The limiter allows 5 attempts a minute per IP and email, then answers 429. |
Related Documentation#
- Two-Factor Authentication: enrolling and the challenge in detail.
- Social Login: Google, Apple, GitHub and Microsoft sign-in.
- Sign-in Handoff: carrying a signed-in session into a browser.
- Configuration:
auth.*,frontend_urland token lifetimes.