# Bearer Token Testing Guide

## Overview

After logging in through the web interface, a Sanctum bearer token is automatically generated and stored in the session. This guide shows you how to retrieve and use it for API authentication.

---

## 🔐 Step 1: Login via Web Browser

First, log in through the web interface to generate the token:

**Login URL:** `http://demo.localhost:8000/login`

**Credentials:**

- Email: `admin@example.com`
- Password: `password`

**What happens behind the scenes:**

1. User credentials are validated
2. User is authenticated via session
3. **Sanctum token is generated** with name `auth_token`
4. Token is stored in session under key `sanctum_token`

**⚠️ Important:** After logging in, your browser stores a session cookie. You MUST include this cookie when calling the API endpoints to retrieve the token.

---

## 🎯 Step 2: Retrieve Bearer Token

### Option 1: Using cURL (Recommended for Testing)

```bash
# Get CSRF token
CSRF=$(curl -X GET http://demo.localhost:8000/login \
  -c /tmp/cookies.txt -s | \
  grep -oP 'csrf-token" content="\K[^"]+' | head -1)

# Login
curl -X POST http://demo.localhost:8000/login \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "X-CSRF-TOKEN: $CSRF" \
  -b /tmp/cookies.txt \
  -c /tmp/cookies.txt \
  -d '{"email":"admin@example.com","password":"password"}' \
  -s -o /dev/null

# Get the token
curl -X GET http://demo.localhost:8000/api/auth/session \
  -H "Accept: application/json" \
  -b /tmp/cookies.txt
```

**Response:**

```json
{
    "success": true,
    "data": {
        "session": {
            "cookie_name": "tenant_demo_session",
            "cookie_received": true,
            "cookie_value": "eyJpdiI6...",
            "session_id": "NbzVZskFrv276SQPWjhoWJdQi61o6CBMvrKhxqS5"
        },
        "authentication": {
            "is_authenticated": true,
            "user_id": 1,
            "user_email": "admin@example.com",
            "sanctum_token": "3|s7czPOG3Z0yB2TOI08VrqJ2KpUTsOPxSZ0tktKM384970f26"
        },
        "debug": {
            "has_session": true,
            "session_started": true,
            "cookie_header_present": true
        }
    }
}
```

**Copy the `sanctum_token` value - this is your Bearer token!**

### Option 2: Using Postman

**Step 1: Login**

- Method: `POST`
- URL: `http://demo.localhost:8000/login`
- Headers:
    - `Content-Type: application/json`
    - `Accept: application/json`
    - `X-CSRF-TOKEN: <get from cookies after visiting /login>`
- Body (JSON):
    ```json
    {
        "email": "admin@example.com",
        "password": "password"
    }
    ```
- ✅ Enable "Save cookies" in Postman

**Step 2: Get Token**

- Method: `GET`
- URL: `http://demo.localhost:8000/api/auth/session`
- Headers:
    - `Accept: application/json`
- The cookies from login will be automatically sent
- Copy the `sanctum_token` value from response

### Option 3: Browser Developer Tools

1. Login via browser: `http://demo.localhost:8000/login`
2. Open Developer Tools (F12)
3. Go to **Console** tab
4. Run this JavaScript:
    ```javascript
    fetch('http://demo.localhost:8000/api/auth/session', {
        credentials: 'include',
        headers: { Accept: 'application/json' },
    })
        .then((r) => r.json())
        .then((d) => console.log('Bearer Token:', d.data.sanctum_token));
    ```
5. Copy the token from console output

---

## 🚀 Step 3: Use Bearer Token for API Calls

### cURL Examples

**Test 1: Verify Authentication**

```bash
TOKEN="3|s7czPOG3Z0yB2TOI08VrqJ2KpUTsOPxSZ0tktKM384970f26"

curl -X GET http://demo.localhost:8000/api/auth/verify \
  -H "Accept: application/json" \
  -H "Authorization: Bearer $TOKEN"
```

**Expected Response:**

```json
{
    "isAuthenticated": true
}
```

### Postman Examples

**Configuration:**

1. Create new request
2. Go to **Authorization** tab
3. Select **Type:** `Bearer Token`
4. Paste your token in the **Token** field
5. Or add header manually:
    - Key: `Authorization`
    - Value: `Bearer 3|s7czPOG3Z0yB2TOI08VrqJ2KpUTsOPxSZ0tktKM384970f26`

**Test Endpoints:**

| Endpoint            | Method | Auth Required | Description                  |
| ------------------- | ------ | ------------- | ---------------------------- |
| `/api/auth/session` | GET    | No            | Get session info and token   |
| `/api/auth/verify`  | GET    | Yes           | Verify authentication status |

---

## 🔄 Complete Testing Workflow

### Full Script (Copy & Run)

```bash
#!/bin/bash

DOMAIN="http://demo.localhost:8000"
EMAIL="admin@example.com"
PASSWORD="password"
COOKIES="/tmp/demo_cookies.txt"

echo "======================================"
echo "   SANCTUM BEARER TOKEN TEST"
echo "======================================"
echo ""

# Step 1: Get CSRF Token
echo "📋 Step 1: Getting CSRF token..."
rm -f $COOKIES
CSRF=$(curl -X GET "$DOMAIN/login" -c $COOKIES -s | \
  grep -oP 'csrf-token" content="\K[^"]+' | head -1)
echo "✅ CSRF Token: $CSRF"
echo ""

# Step 2: Login
echo "🔐 Step 2: Logging in..."
LOGIN_STATUS=$(curl -X POST "$DOMAIN/login" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "X-CSRF-TOKEN: $CSRF" \
  -b $COOKIES -c $COOKIES \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}" \
  -s -o /dev/null -w "%{http_code}")
echo "✅ Login Status: $LOGIN_STATUS"
echo ""

# Step 3: Get Token
echo "🎫 Step 3: Retrieving Bearer Token..."
RESPONSE=$(curl -X GET "$DOMAIN/api/auth/session" \
  -H "Accept: application/json" \
  -b $COOKIES -s)
echo "Response: $RESPONSE"
echo ""

# Extract token (requires jq)
TOKEN=$(echo $RESPONSE | grep -oP '"sanctum_token":"\K[^"]+')
echo "🔑 Bearer Token: $TOKEN"
echo ""

# Step 4: Test Token
echo "🧪 Step 4: Testing Bearer Token..."
TEST_RESPONSE=$(curl -X GET "$DOMAIN/api/auth/verify" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer $TOKEN" -s)
echo "✅ Test Response: $TEST_RESPONSE"
echo ""

echo "======================================"
echo "         TEST COMPLETE"
echo "======================================"
echo ""
echo "Your Bearer Token:"
echo "$TOKEN"
echo ""
echo "Use it in API calls with header:"
echo "Authorization: Bearer $TOKEN"
```

**Save as:** `test-bearer-token.sh`
**Run:** `chmod +x test-bearer-token.sh && ./test-bearer-token.sh`

---

## 🛠️ Troubleshooting

### Common Issues with `/api/auth/session` Endpoint

The endpoint provides detailed debug information to help diagnose issues:

**Debug Fields Explained:**

- `cookie_received`: `true` if session cookie was sent with request
- `is_authenticated`: `true` if user is logged in
- `sanctum_token`: The Bearer token (only present if authenticated)
- `session_started`: `true` if session is active
- `cookie_header_present`: `true` if Cookie header exists

**Diagnostic Steps:**

1. **Check if you're sending cookies:**

    ```bash
    # ❌ Wrong - No cookies
    curl http://demo.localhost:8000/api/auth/session

    # ✅ Correct - With cookies
    curl http://demo.localhost:8000/api/auth/session -b /tmp/cookies.txt
    ```

    Look for: `"cookie_received": true`

2. **Check if you're authenticated:**

    ```bash
    curl http://demo.localhost:8000/api/auth/session -b /tmp/cookies.txt
    ```

    Look for: `"is_authenticated": true`

3. **Check if token exists:**
    ```bash
    curl http://demo.localhost:8000/api/auth/session -b /tmp/cookies.txt
    ```
    Look for: `"sanctum_token": "3|..."`

**Common Scenarios:**

| cookie_received | is_authenticated | sanctum_token | Problem         | Solution                     |
| --------------- | ---------------- | ------------- | --------------- | ---------------------------- |
| `false`         | `false`          | `null`        | No cookies sent | Add `-b cookies.txt` to curl |
| `true`          | `false`          | `null`        | Not logged in   | Login first                  |
| `true`          | `true`           | `null`        | Old session     | Logout and login again       |
| `true`          | `true`           | `"3\|..."`    | ✅ Working      | Token ready to use           |

---

### Issue 1: `sanctum_token: null` or `cookie_received: false`

**Cause 1:** Using old session from before token generation was implemented.
**Cause 2:** Not sending cookies with the request.
**Cause 3:** Not logged in.

**Diagnosis:**
Check the `/api/auth/session` response:

- If `cookie_received: false` → You're not sending cookies
- If `is_authenticated: false` → You're not logged in
- If `sanctum_token: null` → Old session, need fresh login

**Solution:**

```bash
# Option 1: Logout and login again
Visit: http://demo.localhost:8000/logout
Then: http://demo.localhost:8000/login

# Option 2: Clear cookies
rm /tmp/cookies.txt  # for cURL
# OR clear browser cookies for demo.localhost:8000

# Option 3: Force new login
curl -X GET http://demo.localhost:8000/logout -b /tmp/cookies.txt
# Then login again
```

### Issue 2: `401 Unauthenticated`

**Possible Causes:**

- Token expired
- Token is invalid
- Wrong domain (tokens are tenant-specific)
- Missing `Bearer` prefix in Authorization header

**Check:**

```bash
# Verify token format
echo "Authorization: Bearer YOUR_TOKEN_HERE"

# Verify authentication
curl -X GET http://demo.localhost:8000/api/auth/verify \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Accept: application/json"
```

### Issue 3: CSRF Token Mismatch

**Solution:**

- Always get fresh CSRF token before login
- Use the same cookie jar for all requests
- Check that cookies are being saved/sent

---

## 📊 API Endpoints Reference

### Authentication Endpoints

#### GET `/api/auth/session`

Get session information including Bearer token.

**Authentication:** Optional (uses session if available)

**Response:**

```json
{
    "success": true,
    "data": {
        "session": {
            "cookie_name": "tenant_demo_session",
            "cookie_received": true,
            "cookie_value": "encrypted_session_value",
            "session_id": "session_id_here"
        },
        "authentication": {
            "is_authenticated": true,
            "user_id": 1,
            "user_email": "admin@example.com",
            "sanctum_token": "3|s7czPOG3..."
        },
        "debug": {
            "has_session": true,
            "session_started": true,
            "cookie_header_present": true
        }
    }
}
```

#### GET `/api/auth/verify`

Verify if user is authenticated.

**Authentication:** Required (session or Bearer token)

**Headers:**

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

**Response:**

```json
{
    "isAuthenticated": true
}
```

---

## 🔒 Security Notes

1. **Never commit tokens** to version control
2. **Tokens are tenant-specific** - each tenant has separate tokens
3. **Tokens persist** until:
    - User logs out
    - Token is manually revoked
    - Database is reset
4. **Session vs Token**:
    - Session: Automatic with cookies (web browser)
    - Bearer Token: Manual with Authorization header (API clients)

---

## 💡 Quick Reference

**Get Token:**

```bash
curl http://demo.localhost:8000/api/auth/session -b cookies.txt
```

**Use Token:**

```bash
curl http://demo.localhost:8000/api/auth/verify \
  -H "Authorization: Bearer YOUR_TOKEN"
```

**Token Format:**

```
{tenant_id}|{token_hash}
Example: 3|s7czPOG3Z0yB2TOI08VrqJ2KpUTsOPxSZ0tktKM384970f26
```

---

## 📝 Notes

- Token is automatically generated on login
- Token is stored in session and database
- Token can be used for stateless API authentication
- Both session and Bearer token authentication are supported
- Use session auth for web browsers
- Use Bearer token for API clients (mobile apps, SPAs, etc.)

---

**Last Updated:** January 6, 2026
