Authentication Guide
Happy Habitat uses JWT (JSON Web Token) based authentication to secure API endpoints and manage user sessions. This guide covers login, registration, password management, and security best practices.Authentication Flow
The authentication system follows this flow:Login
Endpoint
POST /api/auth/login
Authorization: None (public endpoint)
Request
Headers:Response
Success (200 OK):Implementation Details
The login process:- Credential Validation - Username and password are validated
- Password Hashing - BCrypt is used for secure password comparison
- JWT Generation - A signed JWT token is created with user claims
- Token Expiration - Tokens expire after a configured time period
- Session Storage - Frontend stores token in localStorage
- Controller:
HappyHabitat.API/Controllers/AuthController.cs:26 - Service:
HappyHabitat.Infrastructure/Services/AuthService.cs
Registration
Endpoint
POST /api/auth/register
Authorization: None (public endpoint)
Request
Body:The
roleId field determines the user’s role. See the Roles section for available role IDs.Response
Success (200 OK):Password Requirements
JWT Token Structure
Token Claims
The JWT token contains the following claims:nameid- User ID (ClaimTypes.NameIdentifier)unique_name- Usernameemail- User email addressrole- User role codenbf- Not valid before (Unix timestamp)exp- Expiration time (Unix timestamp)iat- Issued at (Unix timestamp)iss- Issuer (configured in appsettings.json)aud- Audience (configured in appsettings.json)
Using the Token
Include the JWT token in the Authorization header for protected endpoints:Roles
Happy Habitat supports six user roles, each with specific permissions.Available Roles
SYSTEM_ADMIN
ID:
11111111-1111-1111-1111-111111111111Full system access. Can manage all communities and users.ADMIN_COMPANY
ID:
22222222-2222-2222-2222-222222222222Manage assigned communities. Limited to specific communities.COMITEE_MEMBER
ID:
33333333-3333-3333-3333-333333333333Committee member with elevated permissions in their community.RESIDENT
ID:
44444444-4444-4444-4444-444444444444Standard resident access. Can manage own profile and submit tickets.RENTER
ID:
55555555-5555-5555-5555-555555555555Tenant with limited access compared to property owners.VIGILANCE
ID:
66666666-6666-6666-6666-666666666666Security personnel with access to visitor and vehicle logs.Role-Based Authorization
Endpoints are protected using role-based authorization attributes:Password Management
Change Password (Authenticated Users)
Endpoint:POST /api/auth/change-password
Authorization: Required (Bearer token)
Request Body:
AuthController.cs:58
Forgot Password
Endpoint:POST /api/auth/forgot-password
Authorization: None (public endpoint)
Request Body:
For security reasons, the API returns a success message regardless of whether the email exists.
AuthController.cs:76
Reset Password
Endpoint:POST /api/auth/reset-password
Authorization: None (requires reset token)
Request Body:
AuthController.cs:91
Token Refresh
Endpoint:POST /api/auth/refresh
Request Body:
- Frontend prepared to use refresh tokens
- Backend endpoint exists but needs token storage logic
- Should be implemented before production deployment
AuthController.cs:105
Security Configuration
JWT Settings
JWT configuration is managed inappsettings.json:
Program.cs:75-88):
Token Validation
Token validation parameters (Program.cs:101-110):
Password Hashing
Passwords are hashed using BCrypt with the following settings:- Algorithm: BCrypt
- Work Factor: 10 (configurable)
- Salt: Auto-generated per password
- Hash Prefix:
$2a$or$2b$
PasswordHasherService in Infrastructure layer
Session Management
Frontend Session Storage
The frontend stores session data in localStorage: Keys:hh_token- JWT access tokenhh_refresh_token- Refresh token (if available)hh_user- User information (JSON)hh_token_expiry- Token expiration timestamp
Checking Authentication Status
On App Initialization:- Retrieve token from localStorage
- Check if token exists
- Validate token expiration
- If valid, restore user session
- If invalid, clear storage and redirect to login
Logout
Process:- Clear all session data from localStorage
- Invalidate authentication signals/state
- Redirect to login page
- (Optional) Call logout endpoint if server-side session tracking is implemented
CORS Configuration
CORS (Cross-Origin Resource Sharing) is configured to allow frontend access. Development Origins:appsettings.json or environment variables:
Program.cs:47-67
Testing Authentication
Using Swagger
- Navigate to the Swagger UI (development only)
- Click “Authorize” button
- Enter:
Bearer <your-jwt-token> - Click “Authorize”
- Test protected endpoints
Using curl
Login:Using Postman
- Create a new request
- Set method and URL
- Go to “Authorization” tab
- Select “Bearer Token”
- Paste your JWT token
- Send request
Common Issues
401 Unauthorized
Causes:- Expired token
- Invalid token
- Missing Authorization header
- Incorrect token format
- Login again to get a new token
- Verify token format:
Bearer <token> - Check token expiration
- Implement token refresh logic
403 Forbidden
Causes:- Valid token but insufficient permissions
- User role doesn’t match endpoint requirements
- Check your user role
- Contact administrator for role upgrade
- Verify endpoint authorization requirements
Token Expiration
Symptoms:- Suddenly logged out
- API returns 401 after working previously
- Implement automatic token refresh
- Show expiration warning to users
- Redirect to login on expiration
Best Practices
Security
- Store tokens securely (httpOnly cookies in production)
- Implement token refresh to avoid repeated logins
- Use HTTPS in production
- Validate JWT on every request
- Implement rate limiting on auth endpoints
- Log authentication failures for security monitoring
User Experience
- Show clear error messages for login failures
- Implement “Remember Me” functionality
- Provide password strength indicators
- Send password reset emails promptly
- Auto-logout on token expiration with notification
Development
- Use environment variables for sensitive config
- Don’t commit tokens or secrets to version control
- Test with different roles and permissions
- Implement proper error handling
- Add logging for debugging authentication issues
Additional Resources
- Administrator Guide - For managing users and permissions
- Configuration Guide - For setting up JWT and security
- Resident Guide - For resident-specific features