基于令牌过期的路由决策
如果您使用 JSON Web 令牌 (JWT) 来保护您的 Angular 应用程序(我建议您这样做),决定是否应该访问路由的一种方法是检查令牌的过期时间.您可能正在使用 JWT 让您的用户访问您后端上受保护的资源。如果是这种情况,如果令牌过期,令牌将无用,因此这很好地表明用户应被视为“未经过身份验证”。
在您的身份验证服务中创建一个方法来检查用户是否已通过身份验证。同样,为了使用 JWT 进行无状态身份验证,这只是令牌是否过期的问题。 angular2-jwt 中的 JwtHelperService 类可用于此目的。
// src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable()
export class AuthService {
constructor(public jwtHelper: JwtHelperService) {}
// ...
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
// Check whether the token is expired and return
// true or false
return !this.jwtHelper.isTokenExpired(token);
}
}
注意:此示例假设您将用户的 JWT 存储在本地存储中。
创建一个实现路由保护的新服务。你可以随意调用它,但是像 auth-guard.service 这样的东西通常就足够了。
// src/app/auth/auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
该服务注入 AuthService 和 Router 并有一个名为 canActivate 的方法。此方法是正确实现 CanActivate 接口所必需的。
canActivate 方法返回一个布尔值,指示是否应允许导航到路线。如果用户未通过身份验证,他们将被重新路由到其他地方,在这种情况下,路由称为 /login。
现在可以将守卫应用于您希望保护的任何路线。
// src/app/app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import {
AuthGuardService as AuthGuard
} from './auth/auth-guard.service';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{ path: '**', redirectTo: '' }
];
/profile 路由现在有一个额外的配置值:canActivate。上面创建的 AuthGuard 被传递给 canActivate 的数组,这意味着它会在有人尝试访问 /profile 路由时运行。如果用户通过了身份验证,他们就会到达路由。如果没有,它们将被重定向到 /login 路由。
注意:canActivate 守卫仍然允许激活给定路由的组件(但不导航到)。如果我们想完全阻止激活,我们可以使用 canLoad 守卫。
更多信息here