Angular Authentication and Authorization

Implementing Authentication with JWT

Backend Setup: Give a mock-up of the backend script that manages user authentication. Clients will send their credentials to server, which will then create a JWT token and sends it back to the customer.

Token Storage: Use a safe place on the client-side to store the JWT token; local storage or session storage can be an option.

Sending Tokens: Send JWT token everytime an authorized request is made to the server for the authenticated endpoints. This verifies the token that the server passes it through and identifies the user the same time.

Using JWT for Authentication

Login Component: Create a login component where users can enter their credentials and submit them to the server.

Authentication Service: Create an authentication service that communicates with the backend server to authenticate users and manage JWT tokens.

Interceptors: Use Angular's HTTP interceptors to automatically attach the JWT token to outgoing HTTP requests.

Protecting Routes and Handling User Roles

Route Guards: In order to safeguard routes, and in cases where transition would based on the authentication status and allowed roles by the user, Angular route guards are used.

                          
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

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

  canActivate(): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

                          
                        

Role-based Authorization: JWT token envelope has user roles that are stored in its payload. Then, develop custom route guards that targeted changing the response based on both the user's role and the routes requested.

                          
// admin.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.hasRole('admin')) {
      return true;
    } else {
      this.router.navigate(['/']);
      return false;
    }
  }
}

                          
                        

Applying Route Guards: Apply route guards to protected routes in your routing configuration.

                          
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AdminComponent } from './admin/admin.component';
import { AuthGuard } from './auth.guard';
import { AdminGuard } from './admin.guard';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard, AdminGuard] },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }