,

Role-based Access Control for Angular 15 Authentication with JSON Server REST API (ADD, EDIT, DELETE, and VIEW access)

Posted by






Angular 15 Authentication

Angular 15 Authentication

In this article, we will discuss how to implement authentication in an Angular 15 application using a JSON server REST API. We will also explore how to add, edit, delete, and view access based on user roles.

Prerequisites

Before we get started, make sure you have the following installed:

  • Node.js
  • Angular CLI
  • JSON server

Setting up JSON server

First, let’s set up a simple REST API using JSON server. Create a new file called db.json and add some sample data:

“`json
{
“users”: [
{ “id”: 1, “username”: “john_doe”, “password”: “password123”, “role”: “admin” },
{ “id”: 2, “username”: “jane_smith”, “password”: “qwerty”, “role”: “user” }
],
“items”: [
{ “id”: 1, “name”: “Item 1”, “ownerId”: 1 },
{ “id”: 2, “name”: “Item 2”, “ownerId”: 2 }
]
}
“`

Next, start the JSON server using the following command:

“`bash
json-server –watch db.json
“`

Creating an Angular 15 application

Now, let’s create a new Angular 15 application using the Angular CLI:

“`bash
ng new authentication-app
cd authentication-app
“`

Implementing authentication

First, install the necessary packages for authentication:

“`bash
npm install @auth0/angular-jwt
“`

Next, create a new service called auth.service.ts to handle authentication:

“`typescript
// auth.service.ts

import { Injectable } from ‘@angular/core’;
import { JwtHelperService } from ‘@auth0/angular-jwt’;

@Injectable({
providedIn: ‘root’
})
export class AuthService {
constructor(private jwtHelper: JwtHelperService) {}

public isAuthenticated(): boolean {
const token = localStorage.getItem(‘token’);
return !this.jwtHelper.isTokenExpired(token);
}

public login(username: string, password: string): void {
// Implement login logic here
// Send a POST request to the JSON server to authenticate the user
}

public logout(): void {
localStorage.removeItem(‘token’);
}

public getRole(): string {
const token = localStorage.getItem(‘token’);
// Use the JWT token to extract the user’s role
// Return the user’s role
}
}
“`

Adding access based on user role

Now, let’s create a simple guard to restrict access based on user roles. Create a new file called role.guard.ts:

“`typescript
// role.guard.ts

import { Injectable } from ‘@angular/core’;
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from ‘@angular/router’;
import { Observable } from ‘rxjs’;
import { AuthService } from ‘./auth.service’;

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

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree | Observable | Promise {
const expectedRole = route.data.expectedRole;
const userRole = this.authService.getRole();

if (!this.authService.isAuthenticated() || userRole !== expectedRole) {
// Redirect to the login page or display an error message
this.router.navigate([‘login’]);
return false;
}

return true;
}
}
“`

Using the role guard in routes

Finally, let’s use the role guard to protect routes based on user roles. Update your app-routing.module.ts file:

“`typescript
// app-routing.module.ts

import { NgModule } from ‘@angular/core’;
import { RouterModule, Routes } from ‘@angular/router’;
import { DashboardComponent } from ‘./dashboard/dashboard.component’;
import { LoginComponent } from ‘./login/login.component’;
import { RoleGuard } from ‘./role.guard’;

const routes: Routes = [
{ path: ”, component: DashboardComponent, canActivate: [RoleGuard], data: { expectedRole: ‘admin’ } },
{ path: ‘login’, component: LoginComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
“`

Conclusion

Congratulations! You have successfully implemented authentication in an Angular 15 application using a JSON server REST API. You have also added access based on user roles by creating a role guard. Feel free to expand on this example by implementing user registration, password recovery, and more.


0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Pathak Brothers
1 year ago

Angular 15 has CanMatch guard…CanActivet is old now. What do you say?

Nikhil ahire
1 year ago

brother when the next video will be come for next operations.

Vijay Kumar
1 year ago

Good Tutorial than you 🙏🏻

Rafael Portal
1 year ago

excellent !

DINESH KUMAR C
1 year ago

super waiting tamil channel