1

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

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

应用程序路由.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 { }

登录组件.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() 方法,并从主组件的 on init 方法中调用它。下面是代码

home.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';
        }
    }

}

将在所有组件中重复相同的操作。

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

4

1 回答 1

4

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

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);

AuthGuard 服务:

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;
    }

}

因此,除非经过身份验证,否则用户无法导航到配置文件/我的配置文件。

于 2018-08-07T05:27:44.100 回答