Implementing Authentication and Authorization in Angular Applications

Angular Authentication and Authorization

Overview

Authentication and authorization are crucial components of web applications that ensure users can securely log in and access resources. This guide focuses on how to implement these concepts in Angular applications.

Key Concepts

Authentication

  • Definition: The process of verifying who a user is.
  • How it works: Users provide credentials (like username and password), which are validated by the server.
  • Example: A user logs in using their email and password.

Authorization

  • Definition: The process of determining what a user can access after they are authenticated.
  • How it works: Based on the user's role or permissions, the application decides which resources or routes the user can access.
  • Example: An admin user can access the admin dashboard, while a regular user cannot.

Implementing Authentication and Authorization in Angular

1. Setting Up Angular Application

  • Create a new Angular project using Angular CLI:
ng new my-app

2. User Login Component

  • Create a login component that captures user credentials.
  • Use Angular forms for input fields:
<form (ngSubmit)="onSubmit()">
  <input type="text" placeholder="Username" [(ngModel)]="username" name="username" required>
  <input type="password" placeholder="Password" [(ngModel)]="password" name="password" required>
  <button type="submit">Login</button>
</form>

3. Authentication Service

  • Create a service to handle authentication logic.
  • Use HTTP requests to communicate with a backend API for user validation.
  • Example of a basic service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class AuthService {
  constructor(private http: HttpClient) {}

  login(username: string, password: string) {
    return this.http.post('/api/login', { username, password });
  }
}

4. Route Guards

  • Implement route guards to protect routes based on user roles.
  • Example of an AuthGuard:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

Conclusion

Implementing authentication and authorization in Angular involves creating a user login system, utilizing a service for managing authentication, and protecting routes with guards. Understanding these concepts is essential for building secure Angular applications.