Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 7 Authentication Guard Service
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from 'src/app/Services/Authentication/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {
constructor(private authService: AuthenticationService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean> | Promise<boolean> | boolean {
if(! state || ! state.url) return false;
let isValid: boolean = this.checkLoggedIn(state.url);
if (isValid) {
if (route.data && route.data.expectedClaim) {
let expectedClaim = route.data.expectedClaim;
isValid = this.checkClaim(expectedClaim);
}
}
return isValid;
}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
if(! route || ! route.path) return false;
let isValid: boolean = this.checkLoggedIn(route.path);
if (isValid) {
if (route.data && route.data.expectedClaim) {
let expectedClaim = route.data.expectedClaim;
isValid = this.checkClaim(expectedClaim);
}
}
return isValid;
}
checkLoggedIn(url: string): boolean {
if(this.authService.checkLoggedIn()) {
return true;
}
this.authService.redirectUrl = url;
this.router.navigate(['/authentication/login']);
return false;
}
checkClaim(claim: string) {
let hasClaim: boolean = false;
if (this.authService.currentUser) {
hasClaim = this.authService.currentUser.claims.indexOf(claim) > -1;
}
return hasClaim;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.