是否可以限制 Angular 路径中特定 :id 的路由访问?使用 Amplify/Cognito
Is it possible to restrict access in Angular Routing for particular :ids in a path? Using Amplify/Cognito
假设我有一个具有以下设置的路由模块:
const routes: Routes = [
{path: 'login', component: LoginComponent},
{path: '', component: MainComponent,
children: [
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{ path: 'dashboard/:id', component: DashboardComponent },
{path: '404', component: HomeComponent},
{path: '**', redirectTo: '/404'}
]
}];
是否可以限制对以下内容的访问:
https://website.com/dashboard/1(只有落入1的用户才能看到1)
https://website.com/dashboard/2(只有属于2的用户才能看到2)
如果 1 转到 dashboard/2,它们将被路由到错误页面,反之亦然。这可能吗?
那是 Guards 的工作。您可以实现 canActivate
函数并向其传递用于识别的首选参数。
class UserToken {}
class Permissions {
canActivate(user: UserToken, id: string): boolean {
return true;
}
}
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
return this.permissions.canActivate(this.currentUser, route.params.id);
}
}
然后用守卫配置你的路线:
{ path: 'dashboard/:id', component: DashboardComponent, canActivate:['Your Guard Name'] },
身份验证成功后,用户将能够继续。失败时,您将使用 angular Router
.
实现重定向逻辑
假设我有一个具有以下设置的路由模块:
const routes: Routes = [
{path: 'login', component: LoginComponent},
{path: '', component: MainComponent,
children: [
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{ path: 'dashboard/:id', component: DashboardComponent },
{path: '404', component: HomeComponent},
{path: '**', redirectTo: '/404'}
]
}];
是否可以限制对以下内容的访问:
https://website.com/dashboard/1(只有落入1的用户才能看到1) https://website.com/dashboard/2(只有属于2的用户才能看到2)
如果 1 转到 dashboard/2,它们将被路由到错误页面,反之亦然。这可能吗?
那是 Guards 的工作。您可以实现 canActivate
函数并向其传递用于识别的首选参数。
class UserToken {}
class Permissions {
canActivate(user: UserToken, id: string): boolean {
return true;
}
}
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
return this.permissions.canActivate(this.currentUser, route.params.id);
}
}
然后用守卫配置你的路线:
{ path: 'dashboard/:id', component: DashboardComponent, canActivate:['Your Guard Name'] },
身份验证成功后,用户将能够继续。失败时,您将使用 angular Router
.