Auth Guard in Angular is a security feature that allows you to restrict access to certain routes in your application based on whether the user is authenticated or not. This tutorial will guide you through implementing an Auth Guard in your Angular application using HTML tags.
Step 1: Create a new Angular project
First, you need to create a new Angular project. You can do this by running the following command in your terminal:
ng new my-auth-guard-app
This will create a new Angular project called my-auth-guard-app
.
Step 2: Create a new Auth Guard
Next, you need to create a new Auth Guard in your Angular project. To do this, run the following command in your terminal:
ng generate guard auth
This will generate a new Auth Guard called auth.guard.ts
in your project.
Step 3: Implement the Auth Guard logic
Open the auth.guard.ts
file and implement the logic to check if the user is authenticated. You can do this by using the canActivate
method. Here is an example implementation:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (localStorage.getItem('user')) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
In this code, we are checking if the user is authenticated by checking if there is a user object saved in the browser’s local storage. If the user is authenticated, we return true and allow the user to access the route. If the user is not authenticated, we redirect them to the login page.
Step 4: Add the Auth Guard to your routes
Next, you need to add the Auth Guard to the routes in your Angular application. Open the app-routing.module.ts
file and import the Auth Guard. Then, add the Auth Guard to the routes that you want to protect. Here is an example implementation:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this code, we are adding the Auth Guard to the home route. This means that the user will only be able to access the home route if they are authenticated.
Step 5: Implement the login page
Finally, you need to implement the login page in your Angular application. Create a new component called login
using the following command:
ng generate component login
In the login
component, add a form for the user to enter their credentials. When the user submits the form, save the user object to the local storage to authenticate the user. Here is an example implementation:
<form (ngSubmit)="login()">
<input type="text" placeholder="Username" [(ngModel)]="username">
<input type="password" placeholder="Password" [(ngModel)]="password">
<button type="submit">Login</button>
</form>
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string;
password: string;
login() {
localStorage.setItem('user', JSON.stringify({ username: this.username }));
}
}
In this code, when the user submits the form, we save the user object to the local storage, which will authenticate the user and allow them to access protected routes.
That’s it! You have successfully implemented an Auth Guard in your Angular application using HTML tags. Now, only authenticated users will be able to access protected routes.