代码之家  ›  专栏  ›  技术社区  ›  Krishna Chaitanya

Angular 5通过身份验证保护所有视图

  •  1
  • Krishna Chaitanya  · 技术社区  · 6 年前

    我正在学习角5。我正在使用Azure ADAL对用户进行身份验证。

    当路径为空时,我将用户路由到登录页。如果用户尚未登录,我们将提供一个登录按钮,单击该按钮后,用户将进入microsoft登录页面。下面是代码。

    app-routing.module.ts程序

    import { NgModule }             from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    
    import { LoginComponent }      from './login/login.component';
    import { HomeComponent }      from './home/home.component';
    
    const routes: Routes = [
        { path: 'home', component: HomeComponent },
        { path: 'login', component: LoginComponent },
        { path: '', redirectTo: '/login', pathMatch: 'full' }
    ];
    
    @NgModule({
        exports: [RouterModule],
        imports: [RouterModule.forRoot(routes)]
    })
    export class AppRoutingModule { }
    

    login.component.ts登录

    import { Component, OnInit } from '@angular/core';
    
    import { Adal5Service } from 'adal-angular5';
    
    const config = {
        tenant: 'xxxxxxx',
        clientId: 'xxxxxx'
    }
    
    @Component({
        selector: 'app-login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
    
        constructor (private service: Adal5Service) {
            this.service.init(config);
        }
    
        ngOnInit() {
            this.service.handleWindowCallback();
    
            if (this.service.userInfo.authenticated) {
                window.location.href = "home";
            }
        }
    
        public isLoggedIn () {
            return this.service.userInfo.authenticated;
        }
    
        public login () {
            this.service.login();
        }
    
    }
    

    login.component.html登录

    <input type="text" placeholder="CWOPA" class="cwopa-field" />
    <button class="login-button" (click)='login()'>Login</button>
    

    但是,当用户键入主屏幕url时,即使用户没有登录,屏幕也会打开。所以我在login.component.ts中添加了一个isLoggedIn()方法,并在home component的on in it方法中调用它。下面是代码

    主页.component.ts

    import { Component, OnInit } from '@angular/core';
    
    import {LoginComponent} from '../login/login.component'
    
    @Component({
        selector: 'app-home',
        templateUrl: './home.component.html',
        styleUrls: ['./home.component.css'],
        providers: [ LoginComponent ]
    })
    export class HomeComponent implements OnInit {
    
        private loginComponent: LoginComponent;
    
        constructor(loginComponent: LoginComponent) { 
            this.loginComponent = loginComponent;
        }
    
        ngOnInit() {
    
            if (!this.loginComponent.isLoggedIn()) {
                window.location.href = '/login';
            }
        }
    
    }
    

    同样的情况将在所有组件中重复。

    我的问题是,每当添加新组件时,如果isLoggedIn方法不是从组件的on init方法调用的,则视图将在没有身份验证的情况下显示。有没有更好的方法来保护应用程序中的所有视图,而不必在组件的on init方法中编写代码?

    1 回复  |  直到 6 年前
        1
  •  4
  •   K. Ayoub    6 年前

    使用路障,这里有一个例子:
    路由:

    import { ModuleWithProviders } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    
    
    import { MyProfileComponent } from './components/profile/my-profile/my-profile.component';
    
    const appRoutes: Routes = [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'profile/my-profile', component: MyProfileComponent, canActivate: [AuthGuardService] }
    ];
    
    export const Routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
    

    AuthGuardService:身份验证服务:

    import { Injectable } from '@angular/core';
    import { CanActivate, Router } from '@angular/router';
    import { SessionStorageService } from 'ngx-webstorage';
    
    @Injectable()
    export class AuthGuardService implements CanActivate {
    
        constructor(public session: SessionStorageService, public router: Router) { }
    
        canActivate(): boolean {
            if (this.session.retrieve("login") == null) {
                this.router.navigate(['home']);
                return false;
            }
            return true;
        }
    
    }
    

    所以在这里,除非经过身份验证,否则用户无法导航到profile/my profile。