Skip to content

Authentication ​

Learn about JWT authentication and session management in the CraftServerManager API.

Overview ​

The CraftServerManager API uses JWT (JSON Web Tokens) for secure authentication. JWTs are stateless, meaning the server doesn't need to maintain session data.

Authentication Flow ​

mermaid
sequenceDiagram
    Player->>Minecraft: /register command
    Minecraft->>Player: Registration code (e.g., "ABC123")
    Player->>Web App: Enter code + credentials
    Web App->>API: POST /api/auth/register
    API->>Web App: Success
    Web App->>API: POST /api/auth/login
    API->>Web App: JWT Token
    Web App->>API: Request with Authorization header
    API->>Web App: Protected resource

Token Structure ​

JWT tokens contain three parts separated by dots:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEyMzQ1fQ.signature
│                                      │                      │
│                                      │                      └─ Signature
│                                      └─ Payload (claims)
└─ Header (algorithm info)

Token Payload ​

Tokens include the following claims:

  • sub: Subject (username)
  • minecraftUsername: Minecraft username
  • isAdmin: Admin status (boolean)
  • iat: Issued at timestamp
  • exp: Expiration timestamp

Security Best Practices ​

Important

  • Never share your JWT token
  • Always use HTTPS in production
  • Tokens expire after a configurable period
  • Store tokens securely (httpOnly cookies or secure storage)

Token Lifetime ​

  • Default: Tokens are valid for 24 hours
  • Refresh: Login again to obtain a new token
  • Expiration: Expired tokens will return 401 Unauthorized

Authorization Header ​

Include your JWT token in the Authorization header for all protected endpoints:

http
GET /api/auth/me HTTP/1.1
Host: localhost:8080
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Role-Based Access ​

Some endpoints require admin privileges:

  • User: Basic authenticated user
  • Admin: Server administrator with elevated privileges

Admin status is determined by:

  1. Minecraft operator status
  2. Role assigned in the user database

TIP

Admin-only endpoints are marked with a 🔒 badge in the documentation.

Common Authentication Errors ​

ErrorCauseSolution
401 UnauthorizedMissing or invalid tokenLogin again to obtain a valid token
403 ForbiddenInsufficient permissionsAdmin privileges required
Token expiredToken has exceeded its lifetimeRe-authenticate to get a new token
Invalid signatureToken has been tampered withUse the original token or login again

Code Examples ​

JavaScript/TypeScript ​

typescript
// Login and store token
async function login(username: string, password: string) {
  const response = await fetch('http://localhost:8080/api/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password })
  });
  
  const data = await response.json();
  if (data.success) {
    localStorage.setItem('token', data.token);
    return data.token;
  }
  throw new Error(data.error);
}

// Make authenticated request
async function getUserInfo(token: string) {
  const response = await fetch('http://localhost:8080/api/auth/me', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  return await response.json();
}

Python ​

python
import requests

def login(username, password):
    response = requests.post(
        'http://localhost:8080/api/auth/login',
        json={'username': username, 'password': password}
    )
    data = response.json()
    if data['success']:
        return data['token']
    raise Exception(data['error'])

def get_user_info(token):
    response = requests.get(
        'http://localhost:8080/api/auth/me',
        headers={'Authorization': f'Bearer {token}'}
    )
    return response.json()

cURL ​

bash
# Login
TOKEN=$(curl -s -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"player","password":"pass"}' | jq -r '.token')

# Use token
curl http://localhost:8080/api/auth/me \
  -H "Authorization: Bearer $TOKEN"

Next Steps ​

Released under the MIT License.