Skip to content

REST API - Authentication

This guide covers authentication in detail, including how to obtain and use access tokens, handle token refresh, and manage user sessions.

📋 Table of Contents


Overview

The HelpDesk Pro API uses Laravel Sanctum for token-based authentication. This provides:

  • ✅ Secure token generation
  • ✅ Stateless authentication
  • ✅ Per-device token management
  • ✅ Easy token revocation

How It Works

  1. User provides credentials (email/password)
  2. API validates credentials
  3. API returns an access token
  4. Client includes token in subsequent requests
  5. API validates token and processes request

Authentication Methods

Bearer Token Authentication

All authenticated requests use the Authorization header with a Bearer token:

Authorization: Bearer 1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Public Endpoints

Some endpoints don't require authentication:

  • POST /api/v1/auth/login
  • POST /api/v1/auth/register
  • POST /api/v1/auth/password/reset
  • POST /api/v1/auth/password/reset/{token}

Protected Endpoints

All other endpoints require a valid Bearer token.


Getting Started

Step 1: Login

First, obtain an access token by logging in:

bash
POST /api/v1/auth/login

Request Body:

json
{
  "email": "user@example.com",
  "password": "your-password"
}

Response:

json
{
  "success": true,
  "data": {
    "user": {
      "id": 1,
      "first_name": "John",
      "last_name": "Doe",
      "email": "user@example.com",
      "role": {
        "id": 2,
        "name": "Agent",
        "slug": "agent"
      },
      "created_at": "2025-01-01T00:00:00.000000Z",
      "updated_at": "2025-01-15T10:30:00.000000Z"
    },
    "token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer"
  },
  "meta": {
    "timestamp": "2025-01-15T10:30:00.000000Z",
    "version": "v1"
  }
}

Step 2: Use the Token

Include the token in the Authorization header for all subsequent requests:

bash
GET /api/v1/tickets
Authorization: Bearer 1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Accept: application/json

Login

Endpoint

POST /api/v1/auth/login

Request

Headers:

Content-Type: application/json
Accept: application/json

Body:

json
{
  "email": "user@example.com",
  "password": "your-password"
}

Response

Success (200):

json
{
  "success": true,
  "data": {
    "user": { ... },
    "token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer"
  }
}

Error (401):

json
{
  "success": false,
  "message": "Invalid credentials",
  "meta": {
    "timestamp": "2025-01-15T10:30:00.000000Z",
    "version": "v1"
  }
}

Example: cURL

bash
curl -X POST https://your-domain.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your-password"
  }'

Example: JavaScript (Fetch)

javascript
const response = await fetch('https://your-domain.com/api/v1/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'your-password'
  })
});

const data = await response.json();

if (data.success) {
  const token = data.data.token;
  // Store token for future requests
  localStorage.setItem('api_token', token);
}

Registration

Endpoint

POST /api/v1/auth/register

Request

Body:

json
{
  "first_name": "John",
  "last_name": "Doe",
  "email": "newuser@example.com",
  "password": "secure-password-123",
  "password_confirmation": "secure-password-123"
}

Response

Success (201):

json
{
  "success": true,
  "data": {
    "user": { ... },
    "token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer"
  }
}

Error (422):

json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "email": ["The email has already been taken."],
    "password": ["The password confirmation does not match."]
  }
}

Example

bash
curl -X POST https://your-domain.com/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "email": "newuser@example.com",
    "password": "secure-password-123",
    "password_confirmation": "secure-password-123"
  }'

Token Management

Get Current User

Retrieve information about the authenticated user:

GET /api/v1/auth/me

Headers:

Authorization: Bearer 1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Accept: application/json

Response:

json
{
  "success": true,
  "data": {
    "id": 1,
    "first_name": "John",
    "last_name": "Doe",
    "email": "user@example.com",
    "role": { ... },
    ...
  }
}

Logout

Revoke the current access token:

POST /api/v1/auth/logout

Headers:

Authorization: Bearer 1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Accept: application/json

Response:

json
{
  "success": true,
  "message": "Logged out successfully",
  "data": null
}

After logout, the token becomes invalid and cannot be used for further requests.


Password Reset

Request Password Reset

Send a password reset link to the user's email:

POST /api/v1/auth/password/reset

Request:

json
{
  "email": "user@example.com"
}

Response:

json
{
  "success": true,
  "message": "Password reset link sent to your email",
  "data": null
}

Reset Password with Token

Reset password using the token from the email:

POST /api/v1/auth/password/reset/{token}

Request:

json
{
  "email": "user@example.com",
  "password": "new-secure-password",
  "password_confirmation": "new-secure-password"
}

Response:

json
{
  "success": true,
  "message": "Password reset successfully",
  "data": null
}

Security Best Practices

1. Store Tokens Securely

❌ Don't:

  • Store tokens in localStorage (XSS vulnerability)
  • Commit tokens to version control
  • Send tokens in URL parameters
  • Log tokens in console or files

✅ Do:

  • Use httpOnly cookies when possible
  • Store tokens in secure, encrypted storage
  • Use environment variables for server-side storage
  • Implement token rotation

2. Handle Token Expiration

Always check for 401 Unauthorized responses and handle token refresh:

javascript
async function makeAuthenticatedRequest(url, options = {}) {
  const token = localStorage.getItem('api_token');
  
  const response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json'
    }
  });
  
  if (response.status === 401) {
    // Token expired or invalid
    // Redirect to login or refresh token
    window.location.href = '/login';
    return;
  }
  
  return response;
}

3. Use HTTPS

Always use HTTPS in production to protect tokens in transit.

4. Implement Token Refresh

For long-lived applications, implement token refresh logic:

javascript
async function refreshToken() {
  // Your refresh logic here
  // This might involve calling a refresh endpoint
  // or re-authenticating the user
}

5. Rate Limiting

Respect rate limits to avoid temporary bans:

  • Authentication endpoints: 5 requests/minute
  • General API: 60 requests/minute

Troubleshooting

Common Issues

401 Unauthorized

Problem: Token is missing, invalid, or expired.

Solutions:

  • Verify token is included in Authorization header
  • Check token format: Bearer {token}
  • Re-authenticate to get a new token
  • Ensure token hasn't been revoked (logout)

403 Forbidden

Problem: User doesn't have permission for the requested resource.

Solutions:

  • Check user role and permissions
  • Verify resource ownership (for user-specific resources)
  • Contact administrator for permission changes

422 Validation Error

Problem: Request data validation failed.

Solutions:

  • Check error messages in response
  • Verify required fields are provided
  • Ensure data types match expected format
  • Review validation rules in documentation

429 Too Many Requests

Problem: Rate limit exceeded.

Solutions:

  • Wait for rate limit window to reset
  • Implement request throttling in your application
  • Check Retry-After header for wait time
  • Consider upgrading API access tier

Debugging Tips

  1. Check Response Headers:

    bash
    curl -v https://your-domain.com/api/v1/auth/me \
      -H "Authorization: Bearer YOUR_TOKEN"
  2. Verify Token Format:

    • Should start with Bearer
    • Token should be a valid string
  3. Test with cURL:

    bash
    curl -X POST https://your-domain.com/api/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{"email":"test@example.com","password":"test"}'
  4. Check Server Logs:

    • Review Laravel logs for detailed error messages
    • Check authentication middleware logs

Next Steps


For additional support, contact our API support team.

Released under the MIT License.