AuthGuard security not working as expected

285 views Asked by At

In Angular I have implemented JWT authentication. While trying to implement AuthGuard security for role based authentication , it is not working

Here is my code..

Auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { User } from '../data/schema/user';
import { TokenStorageService } from '../data/service/token-storage.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    private userSubject: BehaviorSubject<User>;
    constructor(
        private router: Router,
        private tokenStorageService: TokenStorageService
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log("Access token in auth gaurd", this.tokenStorageService.getToken())
        const user = this.tokenStorageService.getUser();
        console.log("Auth gaurd user is "+user.roles);
        if (user) {
            // check if route is restricted by role
           console.log("Authgaurd route route is ", route.data.roles ,route.data.roles.indexOf(user.role) )
            if (route.data.roles && route.data.roles.indexOf(user.role) === -1) {
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
}

TokenStorageService.ts

import { Injectable } from '@angular/core';

const TOKEN_KEY = 'auth-token';
const USER_KEY = 'auth-user';

@Injectable({
  providedIn: 'root'
})
export class TokenStorageService {

  private roles: string[] = [];
  isLoggedIn = false;
  isAdmin = false;
  constructor() { }

  

  public saveToken(token: string): void {
    window.sessionStorage.removeItem(TOKEN_KEY);
    window.sessionStorage.setItem(TOKEN_KEY, token);
  }

  public getToken(): string | null {
    return window.sessionStorage.getItem(TOKEN_KEY);
  }

  public saveUser(user: any): void {
    window.sessionStorage.removeItem(USER_KEY);
    window.sessionStorage.setItem(USER_KEY, JSON.stringify(user));
  }

  public getUser(): any {
    const user = window.sessionStorage.getItem(USER_KEY);
    if (user) {
      return JSON.parse(user);
    }

    return {};
  }
   

  isUserLoggedIn() { 
    return !(this.getUser() === null)
  }

 
  signOut(): void {
    window.sessionStorage.clear();
  }
}

The image of values I am printing from AuthGuard.ts

Here is my schema code..

User.ts

export class User {
    id: number;
    username: string;
    password: string;
    email:string;
    firstName: string;
    lastName: string;
    created_date: Date;
}

roles.ts

import { ERole } from "./ERole";

export class Role {
    userid: number;
    roleid:number
    
}

ERole.ts

export enum ERole {
    user = 'ROLE_USER' ,//1
    mod='ROLE_MODERATOR',//2
    admin = 'ROLE_ADMIN'//3
   
    
}

in sql i have mamy to mamy relationship between role and user

so user and roles have columns as defined in schema and erole table has columns roleid and rolename.

This is how applied AuthGuard in components..

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ERole } from 'src/app/data/schema/ERole';
import { AuthGuard } from 'src/app/helpers/auth.gaurd';
import { CreateProjectCategoryComponent } from './create-project-category.component';

const routes: Routes = [{ path: 'admin/projectCategory/create', 
component: CreateProjectCategoryComponent,
canActivate: [AuthGuard],
data: { roles: [ERole.admin]}
}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CreateProjectCategoryRoutingModule { }

When i click on navigation link.. nothing happens

Please tell me where i am doing wrong , i quite new in angular .

0

There are 0 answers