5

i'm using angular2-jwt package from auth0. Everything works fine, but now i am wondering how to redirect user, who is currently on some path, which is guarded with my auth guard, somewhere else. Now it is redirecting just when is user trying to get to the guarded path.

I know that i can hide objects in my component, but then i must do that in every single guarded component, which is not so clear.

Here are my routes:

    const appRoutes: Routes = [
    {path: 'login', component: LoginComponent},
    {path: 'register', component: RegisterComponent},
    {path: '', component: HomeComponent},
    {path: 'user/edit', component: EditProfileComponent, canActivate: [AuthGuard]},
];

and this is my guard service:

...

    @Injectable()
export class AuthGuard implements CanActivate {

    constructor(private auth: AuthService, private router: Router) {
        }

        canActivate() {
            if (this.auth.loggedIn()) {
                return true;
            }

            this.router.navigate(['/']);
            return false;
        }
    }
Jan Cizmar
  • 372
  • 2
  • 11

1 Answers1

2

Http interceptor

What you can do is implement a HTTP interceptor.

This HTTP interceptor can check for error codes like 401 (not authenticated) and/or 403 (fobidden, not authorized to access). With an implementation like this, you can also set the authorization headers of your requests each time you send a request to the server.

Make sure you are using HttpClient inside your application. The interceptor listens only for requests made by HttpClient.

Implementation

Step 1, create an error interceptor:

import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import 'rxjs/add/operator/do';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private router: Router) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(event => { }, err => {
            if (err instanceof HttpErrorResponse && err.status == 401) {
                this.router.navigateByUrl('/login');
            } else if (err instanceof HttpErrorResponse && err.status == 403) {
                this.router.navigate(['/not-authorized']);
            }
        });
    }
}

Step 2, use the error interceptor:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true
    },
    // ...
]

Useful links:

  • You can find more on interceptors inside the Angular documentation.
  • An implementation on the authentication interceptor is found here.
Brampage
  • 6,014
  • 4
  • 33
  • 47