Lesson 7: Authentication in Angular

angular lesson 8

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:

  • Header: Contains the token type and signing algorithm.
  • Payload: Contains user data (claims).
  • Signature: Used to verify the token’s authenticity.

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:

JSON
{
  "token": "your.jwt.token"
}
Step 2: Angular Login Service

Create a service in Angular that will handle user login and token storage.

TypeScript
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:

TypeScript
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:

TypeScript
{
  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.

TypeScript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { AuthService } from './auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = this.authService.getToken();
    if (token) {
      const cloned = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(cloned);
    } else {
      return next.handle(req);
    }
  }
}

Additionally, handle the automatic logout when the token expires by checking the token’s expiry time.


6. Refreshing Tokens

Many applications require token refresh to ensure the user stays logged in even after token expiration. You can implement a token refresh mechanism where the client requests a new token before the old one expires.


7. Best Practices for Secure Authentication

  • Always use HTTPS to transmit tokens.
  • Store the token securely (preferably in HTTP-only cookies).
  • Use Refresh Tokens to extend user sessions securely.
  • Implement Role-Based Access Control (RBAC) for different levels of user permissions.

8. Conclusion

Implementing secure JWT-based authentication in Angular is critical for protecting sensitive user data and ensuring that only authenticated users can access certain parts of your application. By using Angular’s built-in tools like HttpClient, Interceptors, and Route Guards, you can create a secure, token-based authentication system.


Next Steps

In the next lesson, we’ll cover Role-Based Access Control (RBAC) in Angular, where we will implement different levels of permissions for users based on their roles.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top