Authentication & Security

JWT Authentication 
 The application uses JWT (JSON Web Token) for authentication: 
 
 
 Login Flow : 
 // User logs in
this.apiService.getUser(username, password).subscribe(
 response => {
 // Store JWT token
 localStorage.setItem('jwt', response.token);
 // Navigate to home
 this.router.navigate(['/']);
 }
);
 
 
 
 Token Storage : JWT tokens are stored in localStorage with key 'jwt' 
 
 
 Token Injection : The AuthInterceptor automatically adds the token to all requests: 
 const token = localStorage.getItem("jwt") 
 ? `Bearer ${localStorage.getItem("jwt")}` 
 : "";

const authReq = req.clone({
 headers: req.headers.set("authorization", token)
});
 
 
 
 Token Verification : AuthGuard verifies tokens before allowing access to protected routes 
 
 
 HTTP Interceptor ( auth.interceptor.ts ) 
 Handles authentication and error responses: 
 Features: 
 
 Automatically adds JWT token to request headers 
 Handles 401/403 unauthorized responses 
 Redirects to login on session expiration 
 Shows user-friendly error messages 
 Clears localStorage on auth failure 
 
 Error Handling: 
 private handleAuthError(err: HttpErrorResponse): Observable<any> {
 if (err.status === 401 || err.status === 403) {
 // Show error notification
 this.Toast.fire({
 title: "Sesi berakhir, mohon login kembali",
 icon: "error"
 });
 
 // Redirect to login
 this.router.navigate(["/login"]);
 
 // Clear token
 localStorage.removeItem("jwt");
 }
 return throwError(err);
}
 
 Security Best Practices 
 
 
 Route Guards : Protect sensitive routes with AuthGuard 
 
 Token Expiration : Tokens are verified on each protected route access 
 
 Secure Communication : All API calls use HTTPS 
 
 XSS Protection : Angular's built-in sanitization 
 
 CSRF Protection : Handled by backend API