将参数传递给Guard Angular 2

问题描述 投票:7回答:2

我有一个应用程序,我已设置了Authentication Guard,以确保用户无法访问该应用程序,除非他们已登录,如此

import { Injectable } from '@angular/core';
import {
    CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    CanActivateChild } from '@angular/router';
import { AuthContext } from './auth-context.service';

@Injectable()
export class AuthGuard implements CanActivate {
        constructor(private router: Router, private authContext: AuthContext) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // Check to see if a user has a valid JWT
        if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
            // If they do, return true and allow the user to load the home component
            return true;
        }

        // If not, they redirect them to the login page
        this.router.navigate(['/login']);
        return false;
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }
}

我想为授权添加另一个警卫,以检查用户是否处于某个角色。目前,我正在隐藏基于此角色的导航链接。

 <div *ngIf="userInRole('Admin')">
             This is secret stuff
 </div>

但是如果用户知道路线,他们只需将其插入网址即可。如何将我的“userInRole()”类型功能添加到Guard?我必须传递角色名称并执行签入代码。卫兵支持参数吗?

angular routing
2个回答
9
投票

我找到了解决方案

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { AuthService } from './service/auth.service';

    @Injectable()
    export class IsInRoleGuard implements CanActivate {
        constructor(
            private _authService: AuthService
        ) { }

        async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
            const userRole = this._authService.getRole(); // Get role from service
            if (next.data['roles'].indexOf(userRole) !== -1) {
                return true;
            }
            return false;
        }
    }

并在您的router-config中

import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { RootComponent } from './root/root.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { IsInRoleGuard } from '../../guards/is-in-role.guard';

const routes: Routes = [
    {
        path: '', component: RootComponent, children: [
            {
                path: '', pathMatch: 'full', canActivate: [IsInRoleGuard], component: DashboardComponent, data: {
                    roles: [
                        'admin',
                        'super-admin'
                    ]
                }
            }
        ]
    }
];

export const RouterConfig: ModuleWithProviders = RouterModule.forChild(routes);

5
投票

Guard只是一个实现CanActivate或CanDeactivate的类。但是没有什么能阻止你注入一个能让你回到用户角色的服务(或价值)。例如,

export class AuthGuard implements CanActivate {
        constructor(private router: Router, private authContext: AuthContext, 
             private user: MyUserService) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
          if (!this.user.isAdmin()) return false;
          ...

    }
}

推荐问答