Angular2:防止经过身份验证的用户访问特定路由

时间:2016-08-12 10:35:06

标签: angular angular2-routing

我在routes文件中定义了一些main.ts

const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent } 
];

成功登录后,我希望经过身份验证的用户可以使用特定路由(例如dashboard)。如果没有登录,他们将无法访问dashboard,但他们可以访问关于,主页,登录

我设法限制用户在没有登录的情况下浏览dashboard,使用CanActivate

canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true; 
    }
    this.router.navigateByUrl('/login');
    return false;
  }

但是在成功登录后使用这些路线和CanActivate方法,用户还可以转到loginhome等路线。我怎么能防止这种情况?

N.B。我正在使用angular2 RC4。

3 个答案:

答案 0 :(得分:16)

我做了一些研究,看看是否有可能“否定”#34;一个后卫,但看起来你必须做一个与你的后卫相反的后卫。喜欢:

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './your-auth.service';

@Injectable()
export class PreventLoggedInAccess implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate() {
    return !this.authService.isLoggedIn();
  }
} 

将它添加到你的引导功能中,你就完成了。你只需要做你的路线:

{ path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },

答案 1 :(得分:4)

制作ts文件名auth.guard.ts将以下代码放在

写保护代码

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

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

在路由ts文件中添加以下代码

APP-routing.module.ts

{
      path: 'user', component: UserComponent,canActivate: [AuthGuard] ,
      children: [{ path: 'home', component: HomeComponent },
                 { path: 'view/:id', component: UserViewComponent },
                 { path: 'add', component: UserAddComponent },
                 { path: 'edit/:id', component: UserAddComponent }
                ]  
  },

在app.module.ts文件中添加提供程序

app.module.ts

@NgModule({
  declarations: [
    AppComponent
    --------
  ],
  imports: [
    BrowserModule
    --------
  ],
  providers: [      
    AuthGuard        
  ],
  bootstrap: [AppComponent]
})

答案 2 :(得分:3)

你可以这样写一个警卫:

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

import { AuthService } from './your-auth.service';

@Injectable()
export class UserAccessGuard implements CanActivate {
    constructor(private authService: AuthService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return route.data['onlyGuests'] != authService.isAuthenticated();
    }
}

然后在路线定义中使用它:

const routes: Routes = [
  { path: '', redirectTo: 'home' },

  // accessible only to guests
  {
      path: '',
      component: HomeComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },
  {
      path: 'login',
      component: LoginComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },

  // accessible only to authenticated users
  {
      path: 'dashboard',
      component: DashboardComponent,
      canActivate: [ UserAccessGuard ]
  }
];