Angular:已登录用户的路由访问限制

huangapple go评论116阅读模式
英文:

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)。例如,如果你有一个 LoginComponentMainComponent,你可以使用守卫来检查用户是否已登录。你可以在你的 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: &#39;login&#39;,  component: LoginComponent },
  { path: &#39;&#39;, component: MainComponent ,canActivate: [AuthGuard]},
];

authGaurd:

export class AuthGuard implements CanActivate {
  constructor( private loginService: LoginService, private router: Router) { }

  canActivate(_route: import(&#39;@angular/router&#39;).ActivatedRouteSnapshot, _state: import(&#39;@angular/router&#39;).RouterStateSnapshot): boolean | import(&#39;@angular/router&#39;).UrlTree | import(&#39;rxjs&#39;).Observable&lt;boolean | import(&#39;@angular/router&#39;).UrlTree&gt; | Promise&lt;boolean | import(&#39;@angular/router&#39;).UrlTree&gt; {
    return this.loginService.checkLogin().then(e=&gt;{
      if(e==true) {
          return true;
      } else {
        this.router.navigate([&#39;login&#39;]);
        return false;
      }
    });
  }
}

for further information check docs : https://angular.io/api/router/CanActivate

huangapple
  • 本文由 发表于 2023年5月6日 16:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定