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! šÆ
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.
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
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:
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.
Next, let's implement user registration. In the AuthService, add the following methods:
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:
ng generate component register
Now that we have registration, let's implement user login. Add the following methods to the AuthService:
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.
Now that we can register and log in users, let's protect our application's routes. To achieve this, we'll create an AuthGuard:
ng generate guard auth
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:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent },
{
path: 'protected',
component: ProtectedComponent,
canActivate: [AuthGuard] // Protect this route
}
];To keep the user logged in between sessions, we'll store the user data in a cookie. Update the AuthService's login method:
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:
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;
}What is the purpose of the AuthService in our Angular application?
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! š”š»