用户身份验证时路由无法正常工作

如何解决用户身份验证时路由无法正常工作

所以,我在一个有路由的项目中遇到了问题。我按照以下步骤操作。

  1. 登录系统时,我将令牌和用户名保存在本地存储中。
  2. 登录成功,打开仪表盘页面
  3. 关闭浏览器并再次打开项目。登录页面中的页面路由,仪表板页面中没有,只有当我放置正确的 url 页面路由时才可以。所以数据在本地存储。 在这部分中,我想在仪表板页面中路由页面,而不是在登录中,只有当我在本地存储中有数据用户时。如果本地存储为空,我想在登录页面中路由

我有这个路由:

const routes: Routes = [
  { path: 'login',component: LoginComponent },{ path: 'forgotpassword',component: ForgotPasswordComponent },{ path: '',{ path: 'panel',canActivate: [AuthGuard],loadChildren: () => import('./panel/panel.module').then(m => m.PanelModule) }
];

还有这个路由面板。

const routes: Routes = [
  {
    path: '',component: PanelComponent,canActivateChild: [AuthGuard],children: [
      {
        path: '',pathMatch: 'full',redirectTo: 'dashboard'
      },{
        path: 'dashboard',component: DashboardComponent,data: { allowedRoles: [Role.COMmunitY_ADMIN] }
      },.....
      {
        path: 'documents',component: DocumentComponent,data: { allowedRoles: [Role.CHAIRMAN] }
      },]
  }
];

我有这个 Authguard。

canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      if (this.authService.currentUserLogged){
      return true;
    }
    this.router.navigateByUrl('/');
    return false;
  }

  canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.currentUserLogged) {
      const userRoles = currentUserLogged.user?.user_roles;
      const allowedRoles = route.data.allowedRoles;
      return this.authService.isAuthorized(allowedRoles,userRoles);
    }
    this.router.navigateByUrl('/');
    return false;
  }

更新

authservice.ts

currentUserLogged!: IUserLoggedInAccountDTO;

     constructor(protected httpClient: HttpClient,private router: Router) {
        this.currentUserLogged = this.getUserLoggedInAccount();
      }
    
      private getUserLoggedInAccount = (): IUserLoggedInAccountDTO => (JSON.parse(localStorage.getItem(environment.userLoggedInAccountLocalStorageKey) || '{}'));
    
      isAuthorized(allowedRoles: any,userRoles: any): boolean {
        if (allowedRoles === null || allowedRoles?.length === 0) {
          return true;
        }
        if (userRoles !== null && userRoles?.length !== 0) {
          const userRolesFiltered = userRoles.filter((userRole: any) => formatDate(userRole.end_date,'yyyy-MM-dd','en_US') >= formatDate(new Date(),'en_US'));
          const authorise: boolean = userRolesFiltered.some((userRole: any) => allowedRoles.includes(userRole.role.name));
          if (!authorise) {
            this.router.navigate(['/']);
            return false;
          }
          return true;
        }
        return false;
      }

非常感谢您的回答!

解决方法

访问根页面时,您必须重定向到仪表板页面。

const routes: Routes = [
  { path: 'login',component: LoginComponent },{ path: 'forgotpassword',component: ForgotPasswordComponent },{ path: '',redirectTo: '/panel/dashboard',pathMatch: 'full' },{ path: 'panel',canActivate: [AuthGuard],loadChildren: () => import('./panel/panel.module').then(m => m.PanelModule) }
];

并且您必须在未登录时导航到登录页面。

canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.currentUserLogged.user){
      return true;
    }
    this.router.navigateByUrl('/login');
    return false;
  }

  canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.currentUserLogged.user) {
      const userRoles = currentUserLogged.user.user_roles;
      const allowedRoles = route.data.allowedRoles;
      return this.authService.isAuthorized(allowedRoles,userRoles);
    }
    this.router.navigateByUrl('/login');
    return false;
  }

更新

您应该在 /login 中返回 false 之前导航到 authservice.ts

        if (userRoles !== null && userRoles?.length !== 0) {
          const userRolesFiltered = userRoles.filter((userRole: any) => formatDate(userRole.end_date,'yyyy-MM-dd','en_US') >= formatDate(new Date(),'en_US'));
          const authorise: boolean = userRolesFiltered.some((userRole: any) => allowedRoles.includes(userRole.role.name));
          if (!authorise) {
            this.router.navigate(['/login']);
            return false;
          }
          return true;
        }
        this.router.navigate(['/login']);
        return false;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?