如何限制用户访问未经授权的角度路径



在我的Angular应用程序中有三种类型的用户:admin、brewer(供应商(&最终用户。我想阻止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如何修改它以实现所需的功能。

如果有人能帮忙,我们将不胜感激

我通过使用逻辑、实现了这一点

您可以在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']);
}
}
}

类似地,对于您的所有角色,您可以定义if条件和在他们的主路由上重定向允许如果用户然后是用户的默认页面,如果是super-admin,那么它可能是admin/dashboard任何类似的东西这

第二种方式:

实现这一点的另一种方法是使用ngx权限,使用该权限可以基于角色控制路由。

附上stackblitz演示以获得更多澄清。

官方文件

NPM包装

您可以使用多个if-else条件

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

最新更新