Files
antrean-anjungan/AUTHENTICATION.md
2025-08-14 09:08:34 +07:00

3.0 KiB

JWT Authentication API Documentation

This document describes how to use the JWT authentication system implemented in this API service.

Overview

The API provides JWT-based authentication with the following features:

  • User login with username/password
  • JWT token generation
  • Token validation middleware
  • Protected routes
  • User registration

Endpoints

Public Endpoints (No Authentication Required)

POST /api/v1/auth/login

Login with username and password to receive a JWT token.

Request Body:

{
  "username": "admin",
  "password": "password"
}

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600
}

POST /api/v1/auth/register

Register a new user account.

Request Body:

{
  "username": "newuser",
  "email": "user@example.com",
  "password": "securepassword",
  "role": "user"
}

Response:

{
  "message": "user registered successfully"
}

Protected Endpoints (Authentication Required)

All protected endpoints require a valid JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>

GET /api/v1/auth/me

Get information about the currently authenticated user.

Headers:

Authorization: Bearer <your-jwt-token>

Response:

{
  "id": "1",
  "username": "admin",
  "email": "admin@example.com",
  "role": "admin"
}

Demo Users

The system comes with pre-configured demo users:

Username Password Role
admin password admin
user password user

Using the JWT Token

Once you receive a JWT token from the login endpoint, include it in the Authorization header for all protected endpoints:

curl -X GET http://localhost:8080/api/v1/products \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Token Expiration

JWT tokens expire after 1 hour. When a token expires, you'll need to login again to get a new token.

Environment Variables

To configure JWT authentication, you can set these environment variables:

# JWT Secret (change this in production)
JWT_SECRET=your-secret-key-change-this-in-production

Testing the Authentication

1. Login with demo user

curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}'

2. Use the token to access protected endpoints

# Get user info
curl -X GET http://localhost:8080/api/v1/auth/me \
  -H "Authorization: Bearer <your-token>"

# Get products
curl -X GET http://localhost:8080/api/v1/products \
  -H "Authorization: Bearer <your-token>"

Error Handling

The API returns appropriate HTTP status codes:

  • 200 OK - Successful request
  • 201 Created - Resource created successfully
  • 400 Bad Request - Invalid request data
  • 401 Unauthorized - Invalid or missing token
  • 500 Internal Server Error - Server error