标签: angular2-guards

Angular 2获得当前的防线路线

我的项目中有一个AccessGuard类,它的工作是确定用户是否可以访问该路由.我使用了router.url获取当前路线但是url在导航到新路线之前返回路线,就像我在用户路线中一样,我点击候选路线,所以url返回用户而不是我想要验证访问权限的候选人到路线这是我的路线档案:

const routes:Routes = [
{
    path:'',
    component:PanelComponent,
    canActivate:[AuthGuard,AccessGuard],
    canActivateChild:[AuthGuard,AccessGuard],
    children:[
        {
            path:'dashboard',
            component:DashboardComponent
        },
        {
            path:'users',
            component:UsersComponent
        },
        {
            path:'users/:id',
            component:ShowUserComponent
        },
        {
            path:'candidates',
            component:CandidatesComponent
        },
        {
            path:'permissions',
            component:PermissionsComponent
        },
        {
            path:'holidays',
            component:HolidaysComponent
        },
        {
            path:'candidate/:id',
            component:CandidateComponent
        },
        {
            path:'salary/create',
            component:InsertSalaryComponent
        },
        {
            path:'document/create',
            component:InsertDocumentComponent
        },
        {
            path:'leave/create',
            component:InsertLeaveComponent
        }
    ]
}

];
Run Code Online (Sandbox Code Playgroud)

这是我的门卫:

permissions;
currentRoute;
constructor(private authService:AuthService,private router:Router){
    this.permissions = this.authService.getPermissions();
}

canActivate(){
    return this.checkHavePermission();
}

canActivateChild(){
    console.log(this.router.url);
    return this.checkHavePermission();
}

private checkHavePermission(){
    switch (this.router.url) { …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-guards angular

25
推荐指数
2
解决办法
2万
查看次数

如何进行单元测试可以使用Jasmine激活angular2的防护方法?

很抱歉提出这类问题.但是我无法在编写canActivate防护文件测试时找到任何博客或youtube教程.在官方文件中也没有提到任何内容.

任何帮助都感激不尽.

unit-testing jasmine angular2-guards angular

21
推荐指数
2
解决办法
1万
查看次数

在Angular 2应用程序中为所有路径使用基准防护

canActivate在Angular2中配置路由时有没有办法设置"基础" ?因此,所有路由都由相同的基本检查覆盖,然后每个路由可以进行更细化的检查.

我有这样的AppModule路由:

@NgModule({
    imports: [
        RouterModule.forRoot([
            {
                path: '',
                component: HomeComponent,
                canActivate: [AuthenticationGuardService],
                data: { roles: [Roles.User] }
            }
        ])
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

对于功能模块FeatureModule:

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: "feature",
                component: FeatureComponent,

                // I'd like to avoid having to do this:
                canActivate: [AuthenticationGuardService],
                data: { roles: [Roles.User] }
            }
        ])
    ],
    exports: [
        RouterModule
    ]
})
export class FeatureRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

AuthenticationGuardService通过使用中提供的角色检查用户是否可以访问路由data …

angular2-routing angular2-guards angular

14
推荐指数
2
解决办法
5559
查看次数

angular2:CanDeactivate guard

我创建了一个CanDeactivate防护,它返回一个observable,它应用于一个加载在内部嵌套路由器插座中的组件.每当有人试图导航到另一个URL时,是否应该调用此警卫?我问这个是因为我的情况并没有发生这种情况.

在我的情况下,警卫只会被调用第一个"不同"的URL.让我试着用一个例子来解释它.假设我总是返回false并且我试图从同一个组件导航到不同的url:

/A --> guard called
/B --> guard called
/B --> no navigation and no guard called
/A --> guard called
/A -->guard not called and no navigation
Run Code Online (Sandbox Code Playgroud)

这是预期的行为吗?

编辑好吧,它似乎是.刚刚建立了一个包含3个组件的小样本,只有在用户第一次尝试导航到特定网址时才会调用防护...这真的很奇怪......

无论如何,这是我正在使用的代码:

// app.routing
import {NgModule} from "@angular/core";
import {Routes, RouterModule, Route, CanDeactivate, ActivatedRouteSnapshot, 
        RouterStateSnapshot} from "@angular/router";
import { MainComponent } from "./main/main.component";
import { OtherComponent } from "./other/other.component";
import { Other3Component } from "./other3/other3.component";
import {Observable} from "rxjs/observable";
const fallback: Route = {
    path: "**",
    redirectTo: "/main",
    pathMatch: …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-guards angular

14
推荐指数
2
解决办法
1万
查看次数

Angular 2如何在同一路径上应用具有Or-Relationship的多个防护

我的应用程序允许基于用户角色访问内容.我为每个角色写了一个Router Guard.某些内容允许访问role1或role2或role3.我应该如何在feature-routing.module.ts文件中编写canActivate声明?据我了解,如果我写

canActivate:[Role1Guard, Role2Guard, Role3Guard]
Run Code Online (Sandbox Code Playgroud)

如果任何警卫返回false,则拒绝访问.但在我的情况下,如果任何一个守卫返回true,我应该允许访问.怎么做?提前谢谢了!

angular2-routing angular2-guards angular

13
推荐指数
1
解决办法
4136
查看次数

Angular2:Global Guard(用户必须始终登录)

我正在构建一个应用程序,对于未经身份验证的用户,根本无法访问.

我写了一个LoggedInGuard,但现在我必须添加canActivate: [LoggedInGuard]到我的路由器配置中的每个路由(除了LoginComponent).

有没有更好的方法让这个工作?


我的文件/模块布局如下所示:

app/
  AppModule
  AppRoutingModule
  AppComponent

  authentication/
    AuthenticationModule
    AuthenticationRoutingModule
    LoginComponent

  contacts/
    ContactsModule
    ContactsRoutingModule
    ContactListComponent

  users/
    UsersModule
    UsersRoutingModule
    UserEditComponent

  ...
Run Code Online (Sandbox Code Playgroud)

也许可以创建两个单独的路由空间(一个用于登录,一个用于应用程序的其余部分)并且仅将防护应用于应用程序部分的其余部分?


我希望有一个简单的解决方案.

提前致谢!

angular2-routing angular2-guards angular

9
推荐指数
2
解决办法
6592
查看次数

试图了解CanActivate和CanActivateChild之间的差异

所以,我试图通过使用警卫来保护对多条路线的访问.我正在使用以下路由来执行此操作:

const adminRoutes : Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [ AuthGuardService ],
    children : [
      {
        path: '',
        canActivateChild: [ AuthGuardService ],
        children: [
          { path: 'edit', component: DashboardComponent},
          { path: '', component: DashboardComponent}
        ]
      }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

这是一个AuthGuardService看起来像什么的看

import { Injectable } from '@angular/core';
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";

@Injectable()
export class AuthGuardService implements CanActivate{

  constructor(private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    console.log("Guarding...");
    return this.sessionValid();
  }

  canActivateChild(route: ActivatedRouteSnapshot, …
Run Code Online (Sandbox Code Playgroud)

angular2-guards angular

9
推荐指数
1
解决办法
4480
查看次数

Angular2路由保护返回Observable <bool>,如何处理错误

我有一个像下面这样的路线保护

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router, private authenticationSvc: AuthenticationService) { }

canActivate(): Observable<boolean> {
    return this.authenticationSvc.getAuthenticatedUser().map(
        r => {
            if (this.authenticationSvc.isAuthenticated()) {
                // logged in so return true
                return true;
            }
            this.router.navigateByUrl('/login');
            return false;
        })
}
Run Code Online (Sandbox Code Playgroud)

问题是有时getAuthenticatedUser返回401,我有一个http拦截器来处理401并重定向到登录页面.问题是这个.map永远不会解析,因为http请求会抛出错误,并且角度路由器会卡在第一个路由请求上,无法处理来自拦截器的后续请求.如何处理此错误并将Observable返回的解析为false并保持移动?

  getAuthenticatedUser() {
         let getUserObservable = this.http.get(ApiUrl + 'security/getAuthenticatedUser')
            .map((res: any) => res.json())
            .share()

        //Get the result for the cache
        getUserObservable.subscribe(
            r => {
                if (r.success) {
                    this.authenticatedUser = r.result.user;
                }
            }); 

        //return the observable
        return getUserObservable;
  } 
Run Code Online (Sandbox Code Playgroud)

和http-intercepter下面 …

javascript rxjs typescript angular2-guards angular

8
推荐指数
1
解决办法
1万
查看次数

使用CanActivate防护时获取"无提供程序错误"

这是警卫:

// my.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';

Injectable()
export class MyGuard implements CanActivate {
  canActivate(next: ActivatedRouteSnapshot, prev: RouterStateSnapshot) {
    console.log('GUARD:', next, prev);
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是路由器:

import { RouterConfig } from '@angular/router';
import { MyGuard } from './guards/my.guard';
export const AppRoutes : RouterConfig = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [MyGuard]
  }
];
Run Code Online (Sandbox Code Playgroud)

当页面加载时,我得到:

EXCEPTION: Error: Uncaught (in promise): No provider for MyGuard!
Run Code Online (Sandbox Code Playgroud)

我见过没有教程提到如何注入MyGuard作为提供者.我该怎么做呢?

angular2-routing angular2-guards angular

7
推荐指数
2
解决办法
5857
查看次数

如何制作Angular2 Service单例?

我正试图在我的应用程序中实现一个auth guard.即; 只有经过身份验证的用户才能访问我的应用的某些路由 我跟着这里给出的啧啧.

一旦用户登录,我将我的AuthService中的布尔值更改为true以指示该用户已登录.这需要在应用程序的整个生命周期中保留.

下面给出了源代码:

AUTH-guard.service.ts

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

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {        
    let url: string = state.url;
    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    console.log('Auth Guard Service: ' + this.authService.isLoggedIn);
    if (this.authService.isLoggedIn) { return true; }
    // Store the attempted URL for …
Run Code Online (Sandbox Code Playgroud)

singleton injectable angular2-guards angular

7
推荐指数
1
解决办法
2096
查看次数