我需要做一个角色后卫。
如果用户拥有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]
}
]
答案 0 :(得分:0)
我们将为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;
}
}
希望这个答案有帮助