Angular routing AuthGuard

Ebben a fejezetben a routing-ot állítjuk be és hogy melyik komponenshez férhetnek hozzá csak az authentikált felhasználók.

Telepítsünk routingnak module-t:
# ng generate module app-routing --module app --flat
Az app.module.ts-be importáljuk be:
import {AppRoutingModule, appRoutes} from './app-routing.module';
import {RouterModule} from '@angular/router';

    imports: [
   ...
        RouterModule.forRoot(appRoutes)
    ],

Az app.component.html -be szúrjuk be:
<router-outlet></router-outlet>

A generált app-routing fájl tartalmára egy példa. Értelemszerűen az AuthGuard paraméterrel rendelkező route-ok csak authentikációval érhetőek el. A path paraméter a böngészőben ezt a nevet adjuk meg az url mögött.
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {UsersComponent} from './modules/core/components/users/users.component';
import {HomeComponent} from './modules/core/components/home/home.component';

export const appRoutes: Routes = [

    {path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
    {
        path: 'signup', component: SignUpComponent,
        children: [{path: '', component: SignUpComponent}]
    },
        path: 'login', component: SignInComponent,
        children: [{path: '', component: SignInComponent}]
    },

    {path: 'users', component: UsersComponent, canActivate: [AuthGuard]},
    {path: 'test1', component: Test2Component, canActivate: [AuthGuard]},
    {path: 'test2', component: Test2Component, canActivate: [AuthGuard]},
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, {useHash: true})],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

Az AuthGuard-al tudjuk védeni a komponenseinket az authentikáció nélküli felhasználóktól.

app.module.ts:
import {AuthGuard} from './modules/components/auth/auth.guard';
import {AuthInterceptor} from './modules/components/auth/auth.interceptor';

    providers: [..., 
        AuthGuard,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true
        },

Az AuthGuard-al visszairányítjuk a login oldalra a felhasználókat és töröljük az összes elmentett adatukat a localestorage-ból biztonsági okokból.
Az auth.interceptor.ts:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpUserEvent, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/do';
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private router: Router) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        if (req.headers.get('No-Auth') == "True") {
            return next.handle(req.clone());
        }

        if (localStorage.getItem('userToken') != null) {
            const clonedreq = req.clone({
                headers: req.headers.set("Authorization", "Bearer " + localStorage.getItem('userToken'))
            });
            return next.handle(clonedreq)
                .do(
                    succ => { },
                    err => {
                        if (err.status === 401){
                            localStorage.removeItem('userToken');
                            localStorage.removeItem('refreshToken');
                            localStorage.removeItem('userName');
                            this.router.navigateByUrl('/login');
                        }
                    }
                );
        }
        else {
            localStorage.removeItem('userToken');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userName');
            this.router.navigateByUrl('/login');
        }
    }
}

Az auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router : Router){}
    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot):  boolean {
        if (localStorage.getItem('userToken') != null){
            return true;
        }

        localStorage.removeItem('userToken');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('userName');
        this.router.navigate(['/login']);
        return false;
    }
}

A következő részben az authentikációt valósítjuk meg jwt-vel.

https://angular.io/guide/router
https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
https://angular.io/api/common/http/HttpInterceptor
https://angular.io/guide/http
https://stackoverflow.com/questions/44396890/angular-4-http-interceptor
2018.12.01.