英文:
Angular : Routes access restrictions for Logged users
问题
我需要限制已登录用户在密码过期后被强制更改密码时访问所有路由。
用户在重定向到更改密码屏幕后不应能够操纵地址栏中的URL。
对Angular不熟悉,需要在实现此功能方面寻求帮助。
英文:
I Need to restrict the logged in user from accessing all the routes when the user is forced to change password after its expiry.
The user should not be able to manipulate the URL in the address bar once he is redirected to the change-password screen.
New to Angular and need assistance in implementing this.
答案1
得分: 1
你可以使用守卫(Guards)。例如,如果你有一个 LoginComponent
和 MainComponent
,你可以使用守卫来检查用户是否已登录。你可以在你的 route.module.ts
中定义它。
route.module.ts:
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', component: MainComponent, canActivate: [AuthGuard] },
];
authGaurd(守卫):
export class AuthGuard implements CanActivate {
constructor(private loginService: LoginService, private router: Router) { }
canActivate(_route: import('@angular/router').ActivatedRouteSnapshot, _state: import('@angular/router').RouterStateSnapshot): boolean | import('@angular/router').UrlTree | import('rxjs').Observable<boolean | import('@angular/router').UrlTree> | Promise<boolean | import('@angular/router').UrlTree> {
return this.loginService.checkLogin().then(e => {
if (e == true) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
});
}
}
欲了解更多信息,请查看文档:https://angular.io/api/router/CanActivate
英文:
You can use Guards. For example if you have a LoginComponent
and MainComponent
, you can use a guard to check if the user logged in or not. you can define it in your route.module.ts
route.module.ts:
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', component: MainComponent ,canActivate: [AuthGuard]},
];
authGaurd:
export class AuthGuard implements CanActivate {
constructor( private loginService: LoginService, private router: Router) { }
canActivate(_route: import('@angular/router').ActivatedRouteSnapshot, _state: import('@angular/router').RouterStateSnapshot): boolean | import('@angular/router').UrlTree | import('rxjs').Observable<boolean | import('@angular/router').UrlTree> | Promise<boolean | import('@angular/router').UrlTree> {
return this.loginService.checkLogin().then(e=>{
if(e==true) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
});
}
}
for further information check docs : https://angular.io/api/router/CanActivate
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论