Skip to main content

Overview

The AuthService 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

Injects Angular’s HttpClient for API calls and TokenStorageService for JWT management.

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 username
  • password (string): User’s password
Returns: Observable<AuthResponse>
object
Authentication response from the server
string
JWT token for authenticated requests
string
Token type (typically “Bearer”)
string
Authenticated user’s username
string
User’s role (e.g., “ROLE_ADMIN” or “ROLE_USER”)
Example:
API Endpoint: POST ${API_URL}/login

register()

Registers a new user account.
AuthRequest
required
User registration data containing username and passwordProperties:
  • username (string): Desired username
  • password (string): User’s password
Returns: Observable<any> - Returns plain text response from the server Example:
API Endpoint: 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
Returns: void Behavior:
  • Saves JWT token using TokenStorageService
  • Stores username in localStorage
  • Stores user role in localStorage
Example:

logout()

Clears all authentication data and logs out the current user.
Returns: void Behavior:
  • Removes JWT token using TokenStorageService.signOut()
  • Removes username from localStorage
  • Removes role from localStorage
Example:

isAdmin()

Checks if the current user has admin privileges.
Returns: boolean - true if user has ROLE_ADMIN, false otherwise Example:

isUser()

Checks if the current user has regular user privileges.
Returns: 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