更新时间:2023-02-17 09:29:16
基本上,您需要Guard
才能添加到Route
中.
Basically, you need a Guard
to add to your Route
.
您需要设置一个Service
来存储用户的身份验证状态(例如,在登录时设置),
You need to setup a Service
that will store the authenticated status of your user (that is set when you login for example),
,然后在您的路线上添加guard
,这将检查您的service's boolean state
,并允许或不激活该路线.如果后卫返回true
,则用户可以访问该路由,否则,您需要将其重定向到您的login
并返回false.
and then add a guard
on your route which will check your service's boolean state
, and allow the route to be activated or not. If the guard returns true
, the user can access the route, if not you need to redirect him to your login
and return false.
让我们很容易做到这一点:
Let's make that quite easily :
设置 auth.service.ts :
@Injectable()
export class AuthService {
public isAuthenticated: boolean = false;
constructor(
// Your DI needs
) { }
// Sets the authenticated state
setLoggedInState(): void {
this.isAuthenticated = tokenNotExpired(); // I'm using angular2-jwt for token management
}
}
不要忘记在ngModule()
providers: [
AuthService
]
现在,您可以从组件中调用服务,并通过使用依赖注入调用服务来设置身份验证状态:
Now, you are able to call your service from your component and set the authenticated state by calling your service using Dependency Injection :
onSubmit() {
// I set my authenticated state from the service itself after I got the Token
this.authService.getToken(this.currentUser.email, this.currentUser.password)
.subscribe((token) => {
this.router.navigate(['/dashboard']); // Route that should be accessed upon login
});
}
现在为您的路线添加一个警卫
And now add a guard to your route
设置 auth.guard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
/**
* Protects the routes to reach with authentication
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
if (this.authService.isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
使用守护程序更新您的routes
:
Update your routes
with the guard:
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
不要忘记将防护添加到appModule
的提供程序中(请谨慎提供一次,因为您只需要一个防护实例即可).
Do not forget to add the guard to the providers of your appModule
(And be careful to provide it once as you need only a single instance of your guard).
providers: [
AuthGuard
]
注意:由于您还拥有一个非常小的应用程序,因此您可能将AuthGuard和服务都放在同一providers
数组中.另外,您无需为警卫设置共享服务.
NB : Since you have a really tiny app yet, you will probably have both the AuthGuard and your service in the same providers
array. Also, you don't need to setup a shared service for a guard.