Angular Authentication, Interceptors and Guards

  1. ng new auth-demo Create a new Angular Application
  2. ng g lib authentication Generate the authentication library
  3. ng g c home Generate the Home Component
  4. ng g c user-dashboard Generate the User Dashboard Component
  5. ng g c admin-dashboard Generate the Admin Dashboard Component
export class AuthenticationModule { 
static forRoot(config: LibraryConfig): ModuleWithProviders<AuthenticationModule> {
return { ngModule: AuthenticationModule,
providers: [{provide: 'config', useValue: config}] };
}
}
export const AUTHENTICATION_CONFIG = 
{ authEndpoint: "/users/authenticate", initialPage: "home" };
imports: [ AuthenticationModule.forRoot(AUTHENTICATION_CONFIG) ]
@Injectable() 
export class TokenInterceptor implements HttpInterceptor {
constructor( private authenticationService: AuthenticationService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let user = this.authenticationService.getLoggedUser();
if (user && user.token) {
request = request.clone({ setHeaders:
{ Authorization: `Bearer ${user.token}` } }); }
return next.handle(request);
}
}
@Injectable() 
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authentiationService: AuthenticationService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).
pipe(catchError(err => {
if (err.status === 401) {
this.authentiationService.logout();
location.reload(); }
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
providers: [ 
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor,
multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor,
multi: true}
]
  1. AuthenticationGuard -> check if the user is authenticated and allow him to access Home
  2. RoleGuard -> check if the user has permission to access User or Admin Dashboard.
@Injectable({ providedIn: 'root' }) 
export class AuthenticationGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService ) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
const currentUser = this.authenticationService.getLoggedUser();

if (currentUser) {
return true;
}
this.router.navigate(['/login']); return false; }
}
@Injectable({ providedIn: 'root' }) 
export class RoleGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService ) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
const currentUser = this.authenticationService.getLoggedUser(); const expectedRole = route.data.expectedRole;
if (currentUser.token === expectedRole) {
return true;
}
this.router.navigate(['/home']);
return false;
}
}
const routes: Routes = [ 
{path: 'login', component: LoginComponent},
{path: 'home', component: HomeComponent,
canActivate: [AuthenticationGuard]},
{path: 'admin', component: AdminDashboardComponent,
canActivate: [AuthenticationGuard, RoleGuard],
data: {expectedRole: ROLE.ADMIN}},
{path: 'user', component: UserDashboardComponent,
canActivate: [AuthenticationGuard, RoleGuard],
data: {expectedRole: ROLE.USER}},
{path: '**', component: NotFoundComponent}
];

--

--

--

Senior Front End Software Engineer focused on Angular. Passionate about learning new skills and sharing my knowledge. Blog agdev.tech in progress.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
AG Dev

AG Dev

Senior Front End Software Engineer focused on Angular. Passionate about learning new skills and sharing my knowledge. Blog agdev.tech in progress.

More from Medium

Unit Testing in Angular

How to setup your first Angular app

Working with Filter in Spring Boot And Angular

Creating a Singleton service in Angular