6.6 KiB
Username/Password Authentication Endpoint
Overview
This endpoint allows users to authenticate using their Okta username (email) and password directly via API, without any browser redirects. Perfect for testing with Postman, mobile apps, or other API clients.
Endpoint Details
URL: POST /api/v1/auth/login
Authentication Required: No
Content-Type: application/json
How It Works
- Client sends credentials → Backend validates with Okta
- Okta authenticates → Returns access token
- Backend fetches user info from Okta
- User exists in DB?
- ✅ Yes → Update user info and last login
- ❌ No → Create new user in database (like spectator/approver flow)
- Return JWT tokens → Access token + Refresh token
Request Body
{
"username": "user@example.com",
"password": "YourOktaPassword123"
}
Fields
| Field | Type | Required | Description |
|---|---|---|---|
username |
string | Yes | User's Okta email/username |
password |
string | Yes | User's Okta password |
Response
Success Response (200 OK)
{
"success": true,
"message": "Login successful",
"data": {
"user": {
"userId": "123e4567-e89b-12d3-a456-426614174000",
"employeeId": "EMP001",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe",
"displayName": "John Doe",
"department": "Engineering",
"designation": "Senior Developer",
"role": "USER"
},
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
},
"timestamp": "2024-01-15T10:30:00.000Z"
}
Error Response (401 Unauthorized)
{
"success": false,
"error": "Login failed",
"message": "Authentication failed: Invalid username or password",
"timestamp": "2024-01-15T10:30:00.000Z"
}
Postman Testing
Step 1: Create New Request
- Open Postman
- Create new request: POST
- URL:
http://localhost:5000/api/v1/auth/login- Or your backend URL (e.g.,
https://re-workflow-nt-dev.siplsolutions.com/api/v1/auth/login)
- Or your backend URL (e.g.,
Step 2: Set Headers
Content-Type: application/json
Step 3: Set Request Body
Choose Body → raw → JSON
{
"username": "your-okta-email@example.com",
"password": "your-okta-password"
}
Step 4: Send Request
Click Send and you should receive:
- ✅ User object with details
- ✅ Access token (valid for 24 hours)
- ✅ Refresh token (valid for 7 days)
Step 5: Use Access Token
Copy the accessToken from the response and use it in subsequent API calls:
Headers:
Authorization: Bearer <your-access-token>
User Creation Logic
Scenario 1: User Exists in Okta & Our DB
- ✅ User authenticated
- ✅ User info updated (department, designation, last login, etc.)
- ✅ Tokens returned
Scenario 2: User Exists in Okta but NOT in Our DB
- ✅ User authenticated with Okta
- ✅ New user created in our database with info from Okta:
oktaSub(Okta subject ID)email(primary identifier)employeeId(if available in Okta profile)firstName,lastName,displayNamedepartment,designation,phonerole= "USER" (default)isActive= true
- ✅ Tokens returned
This is the same behavior as when adding a spectator or approver for the first time!
Scenario 3: User Does NOT Exist in Okta
- ❌ Authentication fails
- ❌ Error: "Invalid username or password"
- ❌ No user created in our DB
Important Notes
🔐 Security
- HTTPS Required in Production: Always use HTTPS to protect credentials in transit
- Rate Limiting: Consider adding rate limiting to prevent brute force attacks
- Okta Password Policy: Follows Okta's password complexity requirements
⚙️ Okta Configuration Required
This endpoint uses Resource Owner Password Credentials grant type. Your Okta application must have this enabled:
- Go to Okta Admin Console
- Navigate to Applications → Your Application
- Under General Settings → Grant Types
- Enable: ✅ Resource Owner Password
📝 Token Management
Access Token:
- Valid for: 24 hours
- Used for: API authentication
- Header:
Authorization: Bearer <token>
Refresh Token:
- Valid for: 7 days
- Used for: Getting new access tokens
- Endpoint:
POST /api/v1/auth/refresh
Example Postman Collection
1. Login
POST http://localhost:5000/api/v1/auth/login
Content-Type: application/json
{
"username": "john.doe@royalenfield.com",
"password": "SecurePassword123!"
}
2. Get Current User (Protected Route)
GET http://localhost:5000/api/v1/auth/me
Authorization: Bearer <access-token-from-login>
3. Refresh Access Token
POST http://localhost:5000/api/v1/auth/refresh
Content-Type: application/json
{
"refreshToken": "<refresh-token-from-login>"
}
Troubleshooting
Error: "OKTA_CLIENT_SECRET is not configured"
Solution: Check your .env file has valid Okta credentials:
OKTA_DOMAIN=https://dev-xxxxx.okta.com
OKTA_CLIENT_ID=your_client_id
OKTA_CLIENT_SECRET=your_client_secret
Error: "Authentication failed: invalid_grant"
Possible causes:
- Username or password is incorrect
- User account is locked/suspended in Okta
- Resource Owner Password grant not enabled in Okta
Error: "Authentication failed: invalid_client"
Solution: Verify OKTA_CLIENT_ID and OKTA_CLIENT_SECRET are correct
New User Not Created
Check logs: Backend logs will show if user creation failed and why
npm run dev # Check console output
Comparison: SSO vs Password Login
| Feature | SSO Flow (Browser) | Password Login (API) |
|---|---|---|
| Use Case | Web application login | Postman, Mobile apps, API clients |
| User Experience | Browser redirect to Okta | Direct username/password |
| Security | OAuth 2.0 Authorization Code | Resource Owner Password |
| Best For | Production web apps | Testing, Mobile apps, Internal tools |
| Endpoint | /api/v1/auth/token-exchange |
/api/v1/auth/login |
Next Steps
After successful authentication:
- Store the
accessTokensecurely - Use it in
Authorizationheader for protected endpoints - Refresh it using
refreshTokenbefore expiry - Call
/api/v1/auth/logoutwhen user logs out
Related Endpoints
POST /api/v1/auth/refresh- Refresh access tokenGET /api/v1/auth/me- Get current user profileGET /api/v1/auth/validate- Validate current tokenPOST /api/v1/auth/logout- Logout and clear cookies