Learn Technologies

Angular 8 – Using Guard

In this part of tutorial, i ‘ll show you how you can secure you web site using Guards. So what’s guard and how to use it?

What’s Gard

The guard gives you a chance to clean-up or ask the user’s permission before navigating away from the current view.
There are meany interfaces that you guard can implement, we found:

  • The CanActivate guard (checking route access).
  • The CanActivateChild guard (checking child route access).
  • The CanDeactivate guard (ask permission to discard unsaved changes).
  • The Resolve guard (pre-fetching route data).
  • Lazy loading feature modules.
  • The CanLoad guard (check before loading feature module assets).

You can find more details in the official angular web site.

Using Gards

Under the path /src/app/ create the folder Guards, and inside it, add the file auth-gard.ts.
In our case, we will check if the logged user has the right profile to access ManageUsers component that will be created under /src/app/.
So, how it works? let’s explain this business rules.
If the user has the Manager profile, so he has the right to access the ManageUsers component, unless, redirect him to Sign In page.
If the user is logged with User profile only, so he doesn’t have the right to access this component.
The code will look like:

import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { UsersServiceService } from '../services/users-service.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {

    constructor(private usersService: UsersServiceService, private route: Router) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.usersService.currentUserObject
        if (currentUser && currentUser.profile == 2) {
            return true;
        }

        this.usersService.logout();
        this.route.navigate(['/SignIn'], { queryParams: { returnUrl: state.url } });
        return false;
    }

}

In the canActivate method, we use the UsersService in order to get the current logged user. After that we check if he has the right profile (defined in WebAPI project).

Finally, we use the canActivate in app-routing.modules.ts:

const routes: Routes = [
  { path: 'SignUp', component: SignUpComponent },
  { path: 'SignIn', component: SignInComponent },
  { path: 'Home', component: HomeComponent },
  { path: 'ManageUsers', component: ManageUsersComponent, canActivate: [AuthGuard] },
];

Let’s move to Web Api and define the UserPrfoileEnum under Forms.Emums project.

   public enum UserProfileEnum
    {
        None = 0,
        User = 1,
        Manager = 2
    }

And add new property in UserModel class called profile type of UserProfileEnum.

 public string mobileNumber { get; set; }

 public string Token { get; set; }

 public UserProfileEnum Profile { get; set; }

That’s all wee need, run the application and try to navigate directly to the URL …/ManageUsers. If the user not logged or doesn’t have the right profile, he will be redirected to Sign In page.

You can find the code source in GitHub:
Angular project.
WebAPI project.


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x