Angular2 redirects the user somewhere when the JWT token expires and it is currently in a secure location

I am using angular2 -jwt package from auth0. Everything is working fine, but now I'm wondering how to redirect the user who is currently on some path that is guarded by my security system, somewhere else. Now it is redirected only when the user tries to get to the protected path.

I know that I can hide objects in my component, but then I have to do this in each separate protected 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;
        }
    }
+4
source share
1 answer

Http Interceptor

, HTTP-.

HTTP- , 401 ( ) / 403 (fobidden, ). , .

, HttpClient . , HttpClient.

1, :

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']);
            }
        });
    }
}

2, :

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

:

  • Angular .
  • .
+1

Source: https://habr.com/ru/post/1670241/


All Articles