Skip to content

Instantly share code, notes, and snippets.

@BigBadJock
Created April 13, 2019 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BigBadJock/b1baadf6ff431a71db8edf06ac8a48ce to your computer and use it in GitHub Desktop.
Save BigBadJock/b1baadf6ff431a71db8edf06ac8a48ce to your computer and use it in GitHub Desktop.
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