Authentication in Angular
1. Introduction to Authentication in Angular
Authentication is the process of verifying the identity of a user. In modern web applications, managing authentication securely is essential. Angular provides robust mechanisms to integrate authentication services, such as token-based authentication using JWT. We’ll focus on how to protect routes, manage tokens, and handle user sessions.
2. Understanding JSON Web Tokens (JWT)
JWT is a token format used for securely transmitting information between the client and server. It typically consists of:
JWTs are compact, URL-safe, and allow secure transmission of user data. Angular uses them to authenticate API requests.
3. Implementing JWT-Based Authentication in Angular
Step 1: Backend Setup
To implement JWT, the server must issue a token upon successful login. The token is sent to the client, and all subsequent requests include this token for authentication.
Example login response from the backend:
领英推荐
{
"token": "your.jwt.token"
}
Step 2: Angular Login Service
Create a service in Angular that will handle user login and token storage.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {}
login(username: string, password: string) {
return this.http.post('https://your-api-url.com/login', { username, password });
}
saveToken(token: string) {
localStorage.setItem('jwtToken', token);
}
getToken() {
return localStorage.getItem('jwtToken');
}
logout() {
localStorage.removeItem('jwtToken');
}
}
4. Protecting Routes with Angular Route Guards
Once the user logs in and has the token, we need to protect specific routes that require authentication. This can be done using Route Guards.
Create an AuthGuard service that checks whether the user is authenticated:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
const token = this.authService.getToken();
if (token) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Add the guard to the routes you want to protect:
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard]
}
5. Managing Token Expiry and Automatic Logout
JWT tokens typically have an expiration time, after which they become invalid. You can use Interceptors to check for expired tokens and log the user out automatically.