This project provides a robust token-based authentication backend using Django Rest Framework. It includes endpoints for user registration, login (to obtain a token), logout (to invalidate a token), and a protected example endpoint that requires authentication.
- User Registration (
/api/register/) - User Login (
/api/login/) – Returns an authentication token - User Logout (
/api/logout/) – Invalidates the token - Protected API Endpoint (
/api/protected/) – Accessible only with a valid token - CORS Configured for frontend integration
Follow these steps to get the Django backend up and running on your local machine.
git clone <your-repository-url>
cd token_auth_projectpython -m venv venvmacOS/Linux:
source venv/bin/activateWindows (Command Prompt):
venv\Scripts\activate.batWindows (PowerShell):
venv\Scripts\Activate.ps1pip install -r requirements.txt- Allow CORS from your frontend:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]python manage.py makemigrations
python manage.py migratepython manage.py createsuperuserpython manage.py runserverBackend will be available at: http://127.0.0.1:8000/
All endpoints are prefixed with /api/.
Description: Register a new user.
Request Body:
{
"username": "newuser",
"email": "[email protected]",
"password": "strongpassword123",
"password2": "strongpassword123"
}Success Response:
{
"message": "User registered successfully",
"username": "newuser",
"token": "your_generated_token"
}Description: Authenticate user and obtain token.
Request Body:
{
"username": "existinguser",
"password": "theirpassword"
}Success Response:
{
"message": "Login successful",
"username": "existinguser",
"token": "your_generated_token"
}Description: Logout user and invalidate token.
Headers:
Authorization: Token <your_authentication_token>Success Response:
{
"message": "Logout successful"
}Description: Access a protected endpoint.
Headers:
Authorization: Token <your_authentication_token>Success Response:
{
"message": "Hello, <username>! You are authenticated and can access this protected data.",
"user_id": 1,
"email": "[email protected]"
}Unauthorized Response:
{
"detail": "Authentication credentials were not provided."
} Use tools like curl, Postman, or Insomnia.
curl -X POST -H "Content-Type: application/json" \
-d '{"username": "testuser", "email": "[email protected]", "password": "password123", "password2": "password123"}' \
http://127.0.0.1:8000/api/register/curl -X POST -H "Content-Type: application/json" \
-d '{"username": "testuser", "password": "password123"}' \
http://127.0.0.1:8000/api/login/curl -X GET -H "Authorization: Token YOUR_TOKEN_HERE" \
http://127.0.0.1:8000/api/protected/curl -X POST -H "Authorization: Token YOUR_TOKEN_HERE" \
http://127.0.0.1:8000/api/logout/This project is open-source and free to use.
Feel free to fork the repository and submit pull requests to improve functionality or documentation.