ANGULAR | akveo/nebular 系列 - 6.6. 以使用者認證保護應用程式 | 中文

原文:https://akveo.github.io/nebular/docs/auth/protecting-application-routes#protecting-application-based-on-user-authentication

以使用者認證保護應用程式

根據以下應用程式結構:

  • /pages/* - 保護區僅適用於已認證之使用者
  • /auth/* - 認證區 (登入、註冊等 …) 適用於未認證之使用者

Angular 提供一個容易的方法保護你的路由,稱之為 Router Guard.
以下我們展示如何整合 Nebular 認證保護 /pages/* (保護區)


建立認證守衛 (AuthGuard)

建立 auth-guard.service.tsapp-routing.module.ts 附近,檔案內容像是:

1
2
3
4
5
6
7
8
9
10
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

canActivate() {
return true;
}
}

完成 canActivate 方法

然後 import NbAuthService 以及完成 the canActivate 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { NbAuthService } from '@nebular/auth';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private authService: NbAuthService) {
}

canActivate() {
return this.authService.isAuthenticated(); // canActive 可以回傳 Observable<boolean> 正是 isAuhenticated 回傳的內容
}
}

當 isAuthenticated() 的值為 true 時,路由會被啟用,反之亦然。


註冊 AuthGuard 服務

我們須要註冊服務 AuthGuardapp.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
import { AuthGuard } from '../auth-guard.service';

@NgModule({
imports: [
// ...
],
providers: [
// ...
AuthGuard
]
});


加入守衛 (AuthGuard) 到路由

最後一步 - 將認證守衛 (AuthGuard) 參考到 app-routing.module.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { AuthGuard } from '../auth-guard.service';

// ...

const routes: Routes = [
{
path: 'pages',
canActivate: [AuthGuard], // 這裡告訴 Angular 利用『認證守衛』檢查存取權限
loadChildren: 'app/pages/pages.module#PagesModule'
},
{
path: 'auth',
component: NbAuthComponent,
children: [
// ...
],
},
// ...
];

如果你不是一個受認證的使用者,將無法存取 pages/* 的任何位置。


重新導向未認證之使用者到登入頁

當使用者訪問受限制的頁面時,你可能希望使用者可以重新導向到 auth/login 頁面,稍微修改反映這個邏輯:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { NbAuthService } from '@nebular/auth';
import { tap } from 'rxjs/operators/tap';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private authService: NbAuthService, private router: Router) {
}

canActivate() {
return this.authService.isAuthenticated()
.pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['auth/login']);
}
}),
);
}
}

我們只是檢查 isAuthenticated 返回的值然後簡單的重新導向到登入頁

很簡單! 希望能對你有幫助。



ANGULAR | akveo/nebular 系列 - 6.6. 以使用者認證保護應用程式 | 中文
http://example.com/2018/08/03/auth-guard/
Author
John Doe
Posted on
August 3, 2018
Licensed under