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 resourceToken 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 usernameisAdmin: Admin status (boolean)iat: Issued at timestampexp: 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:
- Minecraft operator status
- Role assigned in the user database
TIP
Admin-only endpoints are marked with a 🔒 badge in the documentation.
Common Authentication Errors
| Error | Cause | Solution |
|---|---|---|
401 Unauthorized | Missing or invalid token | Login again to obtain a valid token |
403 Forbidden | Insufficient permissions | Admin privileges required |
Token expired | Token has exceeded its lifetime | Re-authenticate to get a new token |
Invalid signature | Token has been tampered with | Use 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
- Authentication Endpoints - Complete API reference
- Getting Started - Initial setup guide
- Error Handling - Handle authentication errors