【问题标题】:Angular2: Prevent authenticated users from accessing specific routesAngular2:防止经过身份验证的用户访问特定路由
【发布时间】:2016-08-12 10:35:06
【问题描述】:

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

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,但他们可以访问about,home,login

我已经设法限制用户在没有登录的情况下遍历dashboard,使用CanActivate

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

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

注意我正在使用 angular2 RC4。

【问题讨论】:

  • 为登录和主页创建另一个 CanActivate 以阻止登录用户访问。

标签: angular angular2-routing


【解决方案1】:

我做了一些研究,看看是否有可能“否定”一个守卫,但似乎你必须制作另一个与你的守卫相反的守卫。喜欢:

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。我想过这种方法。但这是唯一的解决方案吗?
  • 我不知道...我会这样做。如果您找到更优雅的解决方案,请告诉我。
  • 我希望你能像这样否定它canActivate: [!LoggedInGuard]
【解决方案2】:

你可以这样写一个守卫:

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 ]
  }
];

【讨论】:

    【解决方案3】:

    让 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]
    })
    

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 1970-01-01
      • 2020-01-01
      • 2016-07-02
      • 1970-01-01
      • 2016-01-15
      • 2017-09-11
      • 2019-08-02
      • 2017-09-26
      相关资源
      最近更新 更多