javascript - 如何通过用户角色保护路由?角
问题描述
我需要做一个角色基础后卫。
如果用户有activeType = 0
他可以访问某些路线。如果用户有activeType = 1
他可以访问其他路线。
我已经有一名守卫用于路线,但如果您已登录或未登录,我需要为另一名守卫添加此守卫,但如何?
userData: User;
authData: AuthData;
constructor(private router: Router,
private userService: UserService,
private location: Location) {
}
canActivate() {
const userData = JSON.parse(localStorage.getItem("userData"));
const authData = JSON.parse(localStorage.getItem("authData"));
const route = this.location.path();
if (!userData && !authData) {
return true;
} else {
if (route == '/login' || route === '/register') {
this.location.back();
return false;
} else {
return true;
}
}
}
canLoad() {
const userData = JSON.parse(localStorage.getItem("userData"));
const authData = JSON.parse(localStorage.getItem("authData"));
if (userData && authData) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.userService.logout();
this.router.navigate(["/login"]);
return false;
}
const routes: Routes = [
{
path: "route-for-user-activeType-1",
loadChildren: () =>
import("./one/one.module").then(
(m) => m.OneModule
),
canLoad: [AuthGuard]
},
{
path: "route-for-user-activeType-0",
loadChildren: () =>
import("./two/two.module").then((m) => m.twoModule),
canActivate: [AuthGuard]
},
{
path: "route-path-for-user-activeType-1",
loadChildren: () =>
import("./test/test.module").then((m) => m.testModule),
canActivate: [AuthGuard]
}
]
解决方案
我们将为 Routes 对象提供有关角色的信息。这个过程很简单。您所要做的就是添加一个守卫并将您的数据添加到角色中。
添加如下守卫,
canActivate: [AuthGuard]
您可以提供将访问该页面的角色信息,如下所示,
data: {
role: 'ROLE_ADMIN'
}`
所以routing-module.ts
应该是这样的。
{
path: 'admin', component: AdminDashboardComponent,
canActivate: [AuthGuard],
data: {
role: 'ROLE_ADMIN'
}
}
创建了一个 Auth 服务,提供有关用户登录状态和角色的信息。我没有任何关于 jwt 令牌实现的集成。这只是一个简单的登录和获取角色的模拟。
@Injectable({
providedIn: 'root'
})
export class AuthService {
isLogin = false;
roleAs: string;
constructor() { }
login(value: string) {
this.isLogin = true;
this.roleAs = value;
localStorage.setItem('STATE', 'true');
localStorage.setItem('ROLE', this.roleAs);
return of({ success: this.isLogin, role: this.roleAs });
}
logout() {
this.isLogin = false;
this.roleAs = '';
localStorage.setItem('STATE', 'false');
localStorage.setItem('ROLE', '');
return of({ success: this.isLogin, role: '' });
}
isLoggedIn() {
const loggedIn = localStorage.getItem('STATE');
if (loggedIn == 'true')
this.isLogin = true;
else
this.isLogin = false;
return this.isLogin;
}
getRole() {
this.roleAs = localStorage.getItem('ROLE');
return this.roleAs;
}
}
AuthGuard.ts
应该
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild, CanDeactivate<unknown>, CanLoad {
constructor(private authService: AuthService, private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
let url: string = state.url;
return this.checkUserLogin(next, url);
}
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.canActivate(next, state);
}
canDeactivate(
component: unknown,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return true;
}
canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
return true;
}
checkUserLogin(route: ActivatedRouteSnapshot, url: any): boolean {
if (this.authService.isLoggedIn()) {
const userRole = this.authService.getRole();
if (route.data.role && route.data.role.indexOf(userRole) === -1) {
this.router.navigate(['/home']);
return false;
}
return true;
}
this.router.navigate(['/home']);
return false;
}
}
希望这个答案有帮助
推荐阅读
- flutter - 如何减少包中的状态管理依赖项?
- javascript - 使用相同的选择器之一但使用默认内容来反应覆盖正确生成的 css 类
- javascript - 推送到数组会删除旧数据(React Native)
- c# - 找不到项目路径中的资源文件夹
- angular - 在 Angular 中取消路由更改的待处理 API 请求是一种好方法吗?无法使用翻译管道显示标题
- powershell - 如何以非交互方式和静默方式卸载 msi
- php - docker 403 禁止 php nginx
- javascript - 使用 JS 函数操作 DOM
- php - 在 PHP 中显示表格
- python - 在python的csv文件中保存具有异构键的对象列表