> For the complete documentation index, see [llms.txt](https://codehas.gitbook.io/the-repairbox/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codehas.gitbook.io/the-repairbox/api-authentication.md).

# API Authentication

RepairBox's API authentication design should distinguish first-party application sessions from credentials issued to external integrations. The intended backend stack uses Laravel Sanctum. Sanctum supports cookie-based authentication for a first-party SPA and bearer tokens for external API clients; these are different modes and should not be mixed casually.

The API endpoints and token-management screens available in a deployed version may differ. Follow the actual API and permission documentation for that release. This page describes the authentication decisions and safe operational pattern.

Official reference: <https://laravel.com/docs/sanctum>

## 1. Choose the correct authentication model

### First-party RepairBox SPA

The React SPA served as part of the same Laravel application should normally use Sanctum's stateful, cookie-based session authentication when the deployment is configured for it. This pattern uses Laravel's session and CSRF protections. It does not require generating long-lived personal access tokens for every frontend request.

Confirm that the expected stateful domain settings, session cookie settings, CORS behavior, and CSRF initialization are configured for the actual deployment. Do not copy an external API token into browser local storage as a substitute for the intended SPA session flow.

### External API client

A server-to-server integration, script, partner application, or other authorized API consumer may use a Sanctum personal access token if the product exposes token issuing and the relevant endpoints permit it.

Tokens should belong to an identified user or integration principal and have a specific purpose, minimal permissions/abilities, a documented owner, and a revocation path. Do not use one all-powerful shared token for every external integration.

### Public widget

A public repair booking or tracking widget is not a trusted staff client. It must not receive an administrator bearer token. Public submission and tracking should use explicitly designed public endpoints, limited fields, server-side validation, rate limiting, and a narrowly scoped access mechanism where the deployed feature supports it.

## 2. Bearer token request format

For a token-authenticated API request, the client typically sends the token in the HTTP Authorization header using the Bearer scheme:

* Header name: Authorization
* Scheme: Bearer
* Value: the secret token issued for that integration

Send JSON with the correct content type and request JSON responses as documented by the API. Use HTTPS in every non-local environment. Never put a token in a URL query string, browser address, analytics event, support ticket, screenshot, source-control commit, or public embed code.

Example structure, using a placeholder rather than a real token:

```
Authorization: Bearer YOUR_SERVER_SIDE_TOKEN
Accept: application/json
```

This example describes the standard request header; it does not imply that every RepairBox endpoint is enabled for token access.

## 3. Token issuance and lifecycle

If the installed RepairBox version exposes token creation, document and manage every part of the token lifecycle.

* **Token name/label:** describe the system and purpose, such as an accounting sync or approved reporting integration. Do not use names containing the secret itself.
* **Owner/principal:** identify which user or integration owns the token.
* **Abilities/scopes:** grant only the operations the client requires, if supported by the API's authorization model.
* **Expiration:** use a short, operationally practical lifetime where configurable. If the deployment uses non-expiring tokens, compensate with strict storage, ownership, rotation, and monitoring policies.
* **Created/last-used metadata:** record and review it where available.
* **Revocation:** disable the token promptly when it is compromised, the integration is removed, or its access is no longer required.
* **Rotation:** create and validate a replacement, update the external consumer securely, then revoke the old token. Do not leave both enabled indefinitely without a reason.
* **Environment:** never reuse production credentials in development/test environments.

A Sanctum token's plain-text form is normally available only at issuance time and should be copied directly to secure secret storage. Do not expect the application database to reveal the original token later.

## 4. Permissions and abilities

Authentication proves which principal is calling; authorization decides what that principal may do. A valid token must not bypass RepairBox policies, outlet restrictions, business ownership checks, or resource-level authorization.

A token ability may narrow the operations permitted by the token, but it is not a replacement for backend policies and permission checks. Every request must still verify:

* The authenticated identity is active and permitted to use the API.
* The route requires the intended authentication method.
* The principal has the required RepairBox permission.
* The requested customer, repair order, repair item, invoice, outlet, or attachment is within the principal's allowed scope.
* The operation is valid for the record's current state.
* The incoming fields are allowed and validated server-side.

Do not rely on React route guards, hidden buttons, or client-supplied role names to authorize an API request.

## 5. Multi-outlet and resource boundaries

RepairBox supports a business with multiple outlets. External API consumers should receive access only to the intended business/outlet and records. A token that can list repairs must not automatically be allowed to retrieve every customer's invoices, attachments, or private notes.

Define and test the scope for:

* Repair Orders and individual Repair Items.
* Customer identity and contact information.
* Catalog data versus private customer-entered custom device details.
* Estimates, invoices, payment records, tax data, and refunds.
* Internal notes, diagnosis details, and attachments.
* Outlets and outlet-specific reporting.
* Notification templates and settings.
* User/role management and audit records.

Avoid exposing broad administrative APIs to integrations that only need to submit booking requests, update a narrow status, or read limited reporting data.

## 6. Error responses and client behavior

A well-behaved client should handle expected authentication/authorization outcomes without leaking secrets.

* **Unauthenticated:** obtain or refresh the intended session/token through the approved process; do not retry forever with the same invalid credential.
* **Forbidden:** the identity was recognized but does not have permission or scope. Do not treat this as an invitation to try another resource ID.
* **Validation error:** correct the input according to documented validation rules.
* **Rate limit:** apply backoff and respect the server's retry guidance if provided.
* **Server error:** use bounded retries for safe/idempotent operations, and investigate using request IDs/logs.
* **Expired/revoked token:** replace it through secure credential management; do not embed a fallback super-admin token in code.

Avoid logging Authorization headers, token values, passwords, session cookies, or CSRF tokens.

## 7. API authentication versus webhooks

A webhook sender such as Stripe or a messaging provider may not authenticate like a normal RepairBox API client. For example, a provider may sign the raw body with a provider-specific secret. Validate that provider's supported signature mechanism rather than expecting a RepairBox Sanctum bearer token in every webhook request.

Similarly, an API bearer token is not a replacement for Stripe's webhook signing secret, a WhatsApp provider's callback validation, or other provider-specific message authentication.

## 8. Recommended integration setup workflow

1. Identify the integration's exact purpose and which API endpoints it needs.
2. Confirm those endpoints exist in the current RepairBox version and are documented in API Endpoints/API Conventions.
3. Create a dedicated integration identity if the product supports it.
4. Grant only the relevant permissions and outlet/resource scope.
5. Issue a token using the supported token-management mechanism.
6. Store the token in the consumer's secret manager or protected deployment environment.
7. Test one authorized read and one intended write in a non-production environment.
8. Test that an out-of-scope outlet, customer, invoice, or permission is rejected.
9. Monitor use and failed requests through approved logs.
10. Record an owner, renewal date/policy, revocation path, and incident contact.

Do not invent an API endpoint or token-management UI. Use the actual OpenAPI/API reference, routes, or supported administration capability for the installed version.

## 9. Security controls

* Require HTTPS outside local development.
* Keep bearer tokens server-side where possible; a browser-based third-party client may require a different design.
* Limit token abilities, owner, outlet scope and lifetime.
* Use separate credentials per system and per environment.
* Rotate exposed secrets immediately.
* Restrict who can issue or revoke tokens.
* Apply rate limiting to authentication and API routes as appropriate.
* Validate data through Form Requests or an equivalent server-side boundary.
* Return dedicated API Resources that expose only fields intended for that client.
* Audit sensitive operations such as invoice/payment changes, reassignment, customer exports and permission changes.
* Keep dependencies and authentication configuration patched.
* Avoid allowing CORS from arbitrary origins simply to resolve a frontend integration error.

## 10. Troubleshooting

**401 Unauthorized:** confirm the route expects the supplied authentication mode, token is present and valid, guard/middleware is configured, and the deployment is using the correct credentials.

**403 Forbidden:** verify the role/permission, token ability if used, outlet assignment, business ownership, record scope, and resource Policy. Do not “fix” this by granting an administrator role to every integration.

**SPA receives 419 or loses session:** check CSRF initialization, cookie domain/secure/same-site settings, stateful domains, HTTPS, and whether the SPA host meets Sanctum's supported domain requirements.

**Token works for some endpoints only:** this can be correct if endpoints use different permissions or authentication guards. Check the exact route middleware, Form Request, Policy and API documentation.

**Token leaks into logs:** remove it from logging/monitoring pipelines, revoke it, create a replacement, and inspect access for possible misuse.

**Cross-outlet records appear:** treat as a security defect. Restrict access on the backend query/policy and test all list, detail, export, relation, and attachment endpoints—not only the main repair list.

## 11. Go-live checklist

* [ ] SPA session authentication and external API token authentication are distinguished.
* [ ] Public widgets do not contain staff/API secrets.
* [ ] Each integration has a named owner and least-privilege access.
* [ ] Token storage, expiry/rotation, and revocation are documented.
* [ ] Backend permissions and resource/outlet policies are enforced.
* [ ] API resources expose only the fields each client requires.
* [ ] HTTPS, rate limiting, safe error handling, and secret-free logging are enabled.
* [ ] Out-of-scope resource access is tested.
* [ ] Provider webhooks use provider-specific signature verification.
* [ ] An incident procedure exists for credential compromise.

## Related documentation

* API Endpoints
* API Conventions
* Authentication with Laravel Sanctum
* Authorization & Permissions
* Webhooks and Notifications
* Embedded Repair Booking Widget
