Overview
In Angular 8 applications, handling authentication and authorization is crucial for security and access control. Authentication verifies a user's identity, while authorization determines their access level. Implementing these features properly is essential for protecting sensitive information and ensuring that users can only access resources they are permitted to.
Key Concepts
- JWT (JSON Web Tokens): A compact, URL-safe means of representing claims to be transferred between two parties.
- AuthGuard: A service in Angular that interfaces with
CanActivate
to guard routes against unauthorized access. - HTTP Interceptors: Angular services that intercept incoming or outgoing HTTP requests using the
HttpClient
. Useful for adding tokens to HTTP requests.
Common Interview Questions
Basic Level
- What is the role of JWT in authentication in Angular applications?
- How do you use Angular services to manage user authentication?
Intermediate Level
- How can you protect routes in Angular using AuthGuard?
Advanced Level
- What is the best practice for handling JWT tokens in Angular for maintaining session and protecting against CSRF and XSS attacks?
Detailed Answers
1. What is the role of JWT in authentication in Angular applications?
Answer: JWT, or JSON Web Token, is a self-contained way for securely transmitting information between parties as a JSON object. In Angular applications, JWTs are often used for authentication and information exchange. When a user logs in, the server creates a JWT and sends it back to the client. The client then stores this token, usually in local storage or session storage, and includes it in the header of future requests to authenticate themselves with the server.
Key Points:
- JWTs contain encoded JSON objects, including claims about an entity (typically, the user) and additional data.
- They are stateless. The server doesn't need to keep a record of tokens.
- Security relies on the token's integrity, which is usually ensured through a digital signature.
Example:
// Example of storing JWT in local storage and adding it to HTTP headers in Angular
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {}
login(userCredentials: any) {
return this.http.post('/api/login', userCredentials).subscribe((response: any) => {
localStorage.setItem('access_token', response.token);
});
}
getAuthToken() {
return localStorage.getItem('access_token');
}
addTokenToHeaders() {
const token = this.getAuthToken();
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
return headers;
}
}
2. How do you use Angular services to manage user authentication?
Answer: Angular services are singleton objects that provide a method of encapsulating and sharing code across your application. For managing user authentication, an Angular service can be used to handle login/logout functionality, token storage, and user state. This service can also interact with Angular's HttpClient to communicate with a backend server for authentication tasks.
Key Points:
- Encapsulates authentication logic for reuse.
- Can be injected into components and other services.
- Maintains user state and token management.
Example:
// AuthService for managing authentication
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isLoggedIn = false;
constructor(private http: HttpClient) {}
login(credentials: {username: string, password: string}) {
return this.http.post('/api/authenticate', credentials).subscribe((response: any) => {
localStorage.setItem('token', response.token);
this.isLoggedIn = true;
});
}
logout() {
localStorage.removeItem('token');
this.isLoggedIn = false;
}
isAuthenticated() {
return this.isLoggedIn;
}
}
3. How can you protect routes in Angular using AuthGuard?
Answer: In Angular, routes can be protected using AuthGuard
which implements the CanActivate
interface. This guard is used in route configuration to decide if a user can navigate to a route based on certain conditions, such as whether the user is authenticated.
Key Points:
- Prevents unauthorized access to routes.
- Can depend on services to check authentication status.
- Easily integrated into the Angular routing module.
Example:
// Example of an AuthGuard
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
4. What is the best practice for handling JWT tokens in Angular for maintaining session and protecting against CSRF and XSS attacks?
Answer: Best practices for handling JWT tokens in Angular include storing tokens securely, using HttpOnly and Secure cookies for storage when possible, and sanitizing data to prevent XSS attacks. Additionally, implementing CSRF protection tokens for requests can help secure your application against CSRF attacks.
Key Points:
- Avoid local storage for token storage, preferring HttpOnly cookies.
- Sanitize all user input to prevent XSS.
- Use CSRF tokens in combination with JWTs for added security.
Example:
Unfortunately, Angular code alone cannot fully illustrate these security measures since they involve server-side settings for cookies and CSRF tokens. However, Angular developers should ensure that they:
- Use the Angular HttpClient
module which is protected against XSS by default.
- Implement server-side logic to set HttpOnly cookies and CSRF tokens.
- Validate the CSRF token in every state-changing request on the server.