如何限制用户访问Angular中未经授权的路径

发布于 2025-01-21 06:11:40 字数 1684 浏览 4 评论 0原文

在我的Angular应用中,有3种类型的用户:管理员,Brewer(供应商)&最终用户。我想防止酿酒师访问管理路线,就像应防止最终用户访问管理员路由和供应商路线一样。

如何通过角路由来实现这一目标。

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home', component: HomeContentComponent,
  },
  { path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
  {
    path: 'admin',
    loadChildren: './modules/admin/admin.module#AdminModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'vendor',
    loadChildren: './modules/vendor/vendor.module#VendoreModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'user',
    loadChildren: './modules/user/user.module#UserModule',
    canActivate: [AuthGuard],
  }
]

auth Guard:

import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
  CanDeactivate,
} from "@angular/router";
import { Observable } from "rxjs";
import { AuthService } from "../services/firebase/auth.service";

@Injectable({ providedIn: "root" })
export class AuthGuard implements CanActivate {
  constructor(public authService: AuthService, public router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    // Guard for userRole is login or not
    // var Role=localStorage.getItem('role')
    let user = localStorage.getItem('toke');
    if (!user) {
      this.router.navigate(["/auth/login"]);
      return true;
    }
    return true;
  }
}

我有这样的auth Guard,我如何对其进行修改以实现所需的功能。

如果有人能提供帮助,将不胜感激。

In my Angular app has 3 types of users: admin, brewer (vendor) & end user. I want to prevent brewer from accessing admin routes, just as end users should be prevented from accessing admin routes and vendor route.

How I can achieve this through angular routing.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home', component: HomeContentComponent,
  },
  { path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
  {
    path: 'admin',
    loadChildren: './modules/admin/admin.module#AdminModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'vendor',
    loadChildren: './modules/vendor/vendor.module#VendoreModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'user',
    loadChildren: './modules/user/user.module#UserModule',
    canActivate: [AuthGuard],
  }
]

Auth Guard :

import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
  CanDeactivate,
} from "@angular/router";
import { Observable } from "rxjs";
import { AuthService } from "../services/firebase/auth.service";

@Injectable({ providedIn: "root" })
export class AuthGuard implements CanActivate {
  constructor(public authService: AuthService, public router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    // Guard for userRole is login or not
    // var Role=localStorage.getItem('role')
    let user = localStorage.getItem('toke');
    if (!user) {
      this.router.navigate(["/auth/login"]);
      return true;
    }
    return true;
  }
}

I have auth guard like this how I can modify it to achieve desired functionality.

It would be greatly appreciated if anyone could help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

糖粟与秋泊 2025-01-28 06:11:40

我已经使用逻辑来实现这一目标,

您可以在 app.component.ts 中使用逻辑

import { Router, NavigationEnd } from '@angular/router';
    
export class AppComponent implements OnInit {
      constructor(
        private router: Router,
      ) {
        this.router.events.subscribe((ev) => {
          if (ev instanceof NavigationEnd) {
    
            const user = localStorage.getItem("Id");
            const Role = localStorage.getItem('UserRole')
            if (user && Role && Role === 'User' && ev.url.includes('/admin)) {
                this.router.navigate(['user/home']);
          }
        }
      }

类似地,对于您的所有角色,您都可以定义条件,并且可以
在其主要路由上重定向,如果用户则是用户的默认页面,
如果超级管理员,则可能是管理员/仪表板
这个。


第二种方法:

另一种实现这一目标的方法是使用 ngx-permissions < /a>使用可以根据角色控制路线的使用。

附加 stackblitz 演示以获取更多澄清。

官方doc

npm软件包

I have achieved this by using logic,

You can use logic like in your app.component.ts

import { Router, NavigationEnd } from '@angular/router';
    
export class AppComponent implements OnInit {
      constructor(
        private router: Router,
      ) {
        this.router.events.subscribe((ev) => {
          if (ev instanceof NavigationEnd) {
    
            const user = localStorage.getItem("Id");
            const Role = localStorage.getItem('UserRole')
            if (user && Role && Role === 'User' && ev.url.includes('/admin)) {
                this.router.navigate(['user/home']);
          }
        }
      }

Similarly for your all roles you can define if condition and can
redirect on their main route lets if user then user's default page,
if super admin then it might be admin/dashboard anything like
this.

Second way:

Another way to achieve this is to use ngx-permissions using which you can control your route based on role.

attaching stackblitz demo for more clarification.

Official doc

NPM Package

旧竹 2025-01-28 06:11:40

如果其他条件,您可以使用多个

const Role = localStorage.getItem('role')
if(Role != "admin"){
    this.router.navigate(["/auth/login"]);
}

you can do it with multiple if else condition

const Role = localStorage.getItem('role')
if(Role != "admin"){
    this.router.navigate(["/auth/login"]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文