255 lines
6.6 KiB
Markdown
255 lines
6.6 KiB
Markdown
# 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
|
|
|
|
1. **Client sends credentials** → Backend validates with Okta
|
|
2. **Okta authenticates** → Returns access token
|
|
3. **Backend fetches user info** from Okta
|
|
4. **User exists in DB?**
|
|
- ✅ Yes → Update user info and last login
|
|
- ❌ No → **Create new user** in database (like spectator/approver flow)
|
|
5. **Return JWT tokens** → Access token + Refresh token
|
|
|
|
## Request Body
|
|
|
|
```json
|
|
{
|
|
"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)
|
|
|
|
```json
|
|
{
|
|
"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)
|
|
|
|
```json
|
|
{
|
|
"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
|
|
|
|
1. Open Postman
|
|
2. Create new request: **POST**
|
|
3. 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`)
|
|
|
|
### Step 2: Set Headers
|
|
|
|
```
|
|
Content-Type: application/json
|
|
```
|
|
|
|
### Step 3: Set Request Body
|
|
|
|
Choose **Body** → **raw** → **JSON**
|
|
|
|
```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`, `displayName`
|
|
- `department`, `designation`, `phone`
|
|
- `role` = "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
|
|
|
|
1. **HTTPS Required in Production**: Always use HTTPS to protect credentials in transit
|
|
2. **Rate Limiting**: Consider adding rate limiting to prevent brute force attacks
|
|
3. **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:
|
|
|
|
1. Go to Okta Admin Console
|
|
2. Navigate to **Applications** → Your Application
|
|
3. Under **General Settings** → **Grant Types**
|
|
4. 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
|
|
```http
|
|
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)
|
|
```http
|
|
GET http://localhost:5000/api/v1/auth/me
|
|
Authorization: Bearer <access-token-from-login>
|
|
```
|
|
|
|
### 3. Refresh Access Token
|
|
```http
|
|
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:
|
|
```env
|
|
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:**
|
|
1. Username or password is incorrect
|
|
2. User account is locked/suspended in Okta
|
|
3. 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
|
|
```bash
|
|
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:
|
|
1. Store the `accessToken` securely
|
|
2. Use it in `Authorization` header for protected endpoints
|
|
3. Refresh it using `refreshToken` before expiry
|
|
4. Call `/api/v1/auth/logout` when user logs out
|
|
|
|
## Related Endpoints
|
|
|
|
- `POST /api/v1/auth/refresh` - Refresh access token
|
|
- `GET /api/v1/auth/me` - Get current user profile
|
|
- `GET /api/v1/auth/validate` - Validate current token
|
|
- `POST /api/v1/auth/logout` - Logout and clear cookies
|
|
|