All Course > Angular > Develop Web Apps Using Angular Feb 16, 2025

Angular Authentication Tutorial: JWT Login & Signup

In the previous lesson, we learned how to make HTTP requests in Angular. We explored how to use Angular’s HttpClient module to send GET, POST, PUT, and DELETE requests to APIs. This knowledge is crucial for building web apps that interact with backend services. Now, we’ll take it a step further by adding authentication and authorization to our app using JSON Web Tokens (JWT).

I recently worked on a project where I needed to add secure user login and signup features to an Angular app. The backend team provided an API that issued JWTs upon successful login. My task was to store these tokens securely and use them to authenticate users for protected routes. At first, I faced challenges in managing token storage and ensuring that the app remained secure. However, by breaking the process into clear steps, I was able to implement a robust solution.

Setting Up the Authentication Service

The first step is to create an Angular service that handles login, signup, and token storage. This service will interact with the backend API and manage user sessions. Here’s how I did it:

Generate a new service using Angular CLI:

ng generate service auth

Inject HttpClient into the service to make API calls:

import { HttpClient } from '@angular/common/http';  
import { Injectable } from '@angular/core';  

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

Add methods for login and signup:

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

signup(user: { name: string, email: string, password: string }) {  
  return this.http.post('/api/signup', user);  
}

Storing the JWT Securely

Once the user logs in, the API returns a JWT, which we need to store securely. I used Angular’s localStorage to save the token, but you can also use sessionStorage for better security.

Add a method to store the token:

storeToken(token: string) {  
  localStorage.setItem('authToken', token);  
}

Add a method to retrieve the token:

getToken() {  
  return localStorage.getItem('authToken');  
}

Add a method to check if the user is logged in:

isLoggedIn() {  
  return !!this.getToken();  
}

Protecting Routes with AuthGuard

To ensure that only logged-in users can access certain routes, I used Angular’s AuthGuard. This guard checks if the user is authenticated before allowing access.

Generate a new guard using Angular CLI:

ng generate guard auth

Implement the guard logic:

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

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

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

Apply the guard to protected routes in the routing module:

```typescript
const routes: Routes = [  
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },  
  { path: 'login', component: LoginComponent }  
];

Adding Login and Signup Components

Next, I created login and signup components to allow users to authenticate. These components use the AuthService to interact with the backend.

Generate login and signup components:

ng generate component login  
ng generate component signup

Add forms to the components and handle form submission:

// login.component.ts  
onSubmit() {  
  this.authService.login(this.loginForm.value).subscribe((response: any) => {  
    this.authService.storeToken(response.token);  
    this.router.navigate(['/dashboard']);  
  });  
}

Testing the Implementation:

Finally, I tested the entire flow to ensure everything worked as expected. I logged in, stored the token, and accessed protected routes. I also tested error handling for invalid credentials.

Conclusion

In this tutorial, we learned how to implement JWT-based authentication in Angular. We created an AuthService to handle login, signup, and token storage, protected routes using AuthGuard, and built login and signup components. This setup ensures that your Angular app is secure and user-friendly.

In the next lesson, we’ll explore how to use RxJS for state management in Angular. This will help you manage complex app states more effectively.

Comments

There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.

Tags: angular typescript