Authentication and Authorization are distinct concepts in Angular applications. Authentication refers to the process of verifying a user’s identity, typically through credentials like username and password. Once authenticated, the application can establish a session for the user.
Authorization, on the other hand, deals with determining what actions or resources an authenticated user is allowed to access within the application. This is usually managed by assigning roles or permissions to users, which dictate their level of access.
In Angular, authentication is often implemented using JSON Web Tokens (JWT) that are sent from the server upon successful login. The token is stored client-side and included in subsequent requests to validate the user’s identity.
For authorization, Angular uses route guards to protect specific routes based on user roles or permissions. Route guards are services implementing the CanActivate or CanLoad interfaces, which determine if a user can access a particular route.
Example of a simple route guard:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AdminGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.authService.isAdmin();
}
}