Angular Tutorial: Auth Service šŸ”šŸ’»

beginner
16 min

Angular Tutorial: Auth Service šŸ”šŸ’»

Welcome to our deep dive into Angular's Auth Service! In this tutorial, we'll learn how to secure user access to our Angular applications by building an Auth Service from scratch. By the end, you'll be able to protect your app like a pro! šŸŽÆ

Why Use an Auth Service? šŸ“

Authenticating users is a crucial part of web development, and Angular's Auth Service simplifies the process by handling authentication tasks for us. It allows us to securely manage user sessions, ensuring that only authorized users can access sensitive areas of our applications.

What You'll Learn šŸ“

  • Creating an Auth Service
  • Setting up authentication using Angular's HttpClient
  • Implementing user registration and login
  • Protecting routes with the AuthGuard
  • Storing user data securely
  • Handling authentication errors

Getting Started šŸ’”

Before we begin, make sure you have Node.js, Angular CLI, and npm installed. Create a new Angular project with the following command:

ng new auth-service-tutorial

Now, navigate into the project directory:

cd auth-service-tutorial

Creating the Auth Service šŸ’”

Let's start by creating our Auth Service. Run the following command to generate the service:

ng generate service auth

Now, open the auth.service.ts file and replace its content with the following:

typescript
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { private apiUrl = 'https://your-api-url.com'; constructor(private http: HttpClient) {} // ... }

šŸ“ Note: Replace 'https://your-api-url.com' with your API's URL.

Registering a User šŸ’”

Next, let's implement user registration. In the AuthService, add the following methods:

typescript
register(user: any): Observable<any> { return this.http.post(`${this.apiUrl}/register`, user) .pipe( tap(res => console.log('Registration successful')), catchError(this.handleError) ); } private handleError(error: HttpErrorResponse) { if (error.status === 0) { // A client-side or network error occurred. Handle it appropriately. console.error('An error occurred:', error.error); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong. console.error( `Backend returned code ${error.status}, body was: ${error.error}` ); } // Return an observable with a user-facing error message. return throwError('An error occurred.'); }

Now, let's create a simple registration form in our app:

  1. Create a new component:
ng generate component register
  1. Implement the registration form in the register.component.ts and register.component.html files.

Logging In a User šŸ’”

Now that we have registration, let's implement user login. Add the following methods to the AuthService:

typescript
login(username: string, password: string): Observable<any> { return this.http.post(`${this.apiUrl}/login`, { username, password }) .pipe( tap(res => { console.log('Login successful'); // Store the user's data securely. }), catchError(this.handleError) ); }

Implement a login form in the app similarly to the registration form.

Protecting Routes šŸ’”

Now that we can register and log in users, let's protect our application's routes. To achieve this, we'll create an AuthGuard:

  1. Generate a new guard:
ng generate guard auth
  1. Implement the AuthGuard in auth.guard.ts:
typescript
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()) { this.router.navigate(['/login']); return false; } return true; } }

Now, in the app-routing.module.ts, use the AuthGuard for the routes you want to protect:

typescript
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'register', component: RegisterComponent }, { path: 'login', component: LoginComponent }, { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] // Protect this route } ];

Storing User Data šŸ’”

To keep the user logged in between sessions, we'll store the user data in a cookie. Update the AuthService's login method:

typescript
login(username: string, password: string): Observable<any> { return this.http.post(`${this.apiUrl}/login`, { username, password }) .pipe( tap(res => { console.log('Login successful'); // Store the user's data securely. this.setUserData(res); }), catchError(this.handleError) ); } private setUserData(user: any) { const expires = new Date(); expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000)); // 1 day document.cookie = `user=${JSON.stringify(user)}; expires=${expires.toUTCString()}`; }

Now, modify the AuthService's isLoggedIn method to check the user data:

typescript
isLoggedIn(): boolean { const user = JSON.parse(this.getUserData()); return user !== null && user.username !== undefined; } private getUserData(): any { const cookies = document.cookie.split(';'); for (let cookie of cookies) { const cookieParts = cookie.trim().split('='); if (cookieParts[0].toLowerCase() === 'user') { return cookieParts[1]; } } return null; }

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the AuthService in our Angular application?

Conclusion āœ…

Congratulations! You've learned how to create an Auth Service in an Angular application, handle user registration, login, and protect routes. You're now well on your way to creating secure web applications with Angular! šŸ’”šŸ’»