Overview
TheAuthService handles all authentication-related operations including user login, registration, logout, and role verification. It integrates with the backend API and uses the TokenStorageService to manage JWT tokens.
Location: src/app/auth/auth.service.ts
Constructor
Properties
string
default:"${environment.apiUrl}/auth"
Base URL for authentication endpoints, configured from environment settings.
Methods
login()
Authenticates a user with username and password.AuthRequest
required
User credentials containing username and passwordProperties:
username(string): User’s usernamepassword(string): User’s password
Observable<AuthResponse>
object
POST ${API_URL}/login
register()
Registers a new user account.AuthRequest
required
User registration data containing username and passwordProperties:
username(string): Desired usernamepassword(string): User’s password
Observable<any> - Returns plain text response from the server
Example:
POST ${API_URL}/register
Response Type: Plain text (string)
saveSession()
Saves authentication data to local storage after successful login.AuthResponse
required
Authentication response containing token, username, and role
void
Behavior:
- Saves JWT token using
TokenStorageService - Stores username in localStorage
- Stores user role in localStorage
logout()
Clears all authentication data and logs out the current user.void
Behavior:
- Removes JWT token using
TokenStorageService.signOut() - Removes username from localStorage
- Removes role from localStorage
isAdmin()
Checks if the current user has admin privileges.boolean - true if user has ROLE_ADMIN, false otherwise
Example:
isUser()
Checks if the current user has regular user privileges.boolean - true if user has ROLE_USER, false otherwise
Example:
Usage Example
Complete authentication flow:Error Handling
All HTTP methods return Observables that may emit errors. Common error scenarios:- 401 Unauthorized: Invalid credentials
- 409 Conflict: Username already exists (registration)
- 500 Server Error: Backend service unavailable
See Also
- TokenStorageService - JWT token management
- AuthInterceptor - Automatic token injection
- AuthGuard - Route protection