api-v1/SETUP_AUTH.md

133 lines
3.6 KiB
Markdown

# Quick Setup Guide - Authentication & Authorization
## 1. Install Dependencies
```bash
cd Backend
npm install
```
This will install:
- `jsonwebtoken` - For JWT token validation
- `axios` - For optional auth service API calls
- `redis` - For distributed rate limiting (optional)
## 2. Configure Environment Variables
The JWT secret **must match** the auth service secret:
```env
# Copy from farm-auth-service/.env
JWT_ACCESS_SECRET=add74b258202057143382e8ee9ecc24a1114eddd3da5db79f3d29d24d7083043
```
Create `.env` file in `Backend/` directory:
```env
PORT=3200
TRUST_PROXY=false
# Auth Service Configuration (REQUIRED)
# BuySellService calls this to validate tokens
AUTH_SERVICE_URL=http://localhost:3000
AUTH_SERVICE_TIMEOUT=5000
# Optional: Redis for rate limiting (if not set, uses in-memory)
# REDIS_URL=redis://localhost:6379
```
## 3. Start the Server
```bash
npm start
```
Server will start on `http://localhost:3200`
## 4. Test the Implementation
### Test from Android App
The Android app's `getUserById` function will:
1. Send JWT token in `Authorization: Bearer <token>` header
2. Call `GET http://localhost:3200/users/:userId`
3. Backend validates token → applies rate limiting → checks authorization → returns user data
### Test with cURL
```bash
# 1. Get token from auth service (via login)
TOKEN="your_access_token_from_login"
# 2. Test GET /users/:userId
curl -X GET http://localhost:3200/users/YOUR_USER_ID \
-H "Authorization: Bearer $TOKEN"
# Expected: Returns user data in JSON format
```
### Test Error Cases
```bash
# No token (should return 401)
curl -X GET http://localhost:3200/users/YOUR_USER_ID
# Response: {"error":"Unauthorized","message":"Missing Authorization header..."}
# Invalid token (should return 401)
curl -X GET http://localhost:3200/users/YOUR_USER_ID \
-H "Authorization: Bearer invalid_token"
# Response: {"error":"Unauthorized","message":"Invalid or expired token"}
# Access other user's profile (should return 403 if not admin)
curl -X GET http://localhost:3200/users/OTHER_USER_ID \
-H "Authorization: Bearer $TOKEN"
# Response: {"error":"Forbidden","message":"Cannot access other users' data"}
```
## 5. Verify End-to-End Flow
1. **Login via Auth Service** → Get JWT token
2. **Android app calls** `GET /users/:userId` with token
3. **Backend validates** token → ✅ Authenticated
4. **Backend checks rate limit** → ✅ Under limit
5. **Backend checks authorization** → ✅ User can access their own profile
6. **Backend fetches user** from database
7. **Backend returns** JSON response
8. **Android app displays** JSON in dialog
## 6. Monitor Logs
All requests are logged with:
- User ID
- Action
- Route
- Status (success/failed/forbidden)
- Timestamp
Check console output for audit logs:
```
[AUDIT] {"timestamp":"...","userId":"...","action":"get_user","route":"/users/...","status":"success",...}
```
## Troubleshooting
### Issue: 401 Unauthorized
- Check that `AUTH_SERVICE_URL` is correct and auth service is running
- Verify token is valid and not expired
- Check token is sent in correct format: `Authorization: Bearer <token>`
- Check auth service logs for validation errors
### Issue: 403 Forbidden
- User is trying to access another user's data
- Check user role matches required roles for route
- Admins can access any user data
### Issue: 429 Too Many Requests
- Rate limit exceeded
- Wait for rate limit window to reset
- Check `X-RateLimit-Reset` header for reset time
### Issue: Redis Connection Errors
- Redis is optional - rate limiting will use in-memory store if Redis unavailable
- Check `REDIS_URL` in `.env` if you want to use Redis