【问题标题】:Angular 6 : Empty path bypass auth guardAngular 6:空路径绕过身份验证保护
【发布时间】:2018-07-31 22:57:14
【问题描述】:

我正在尝试使用 Angular 路由器,但在空路径上遇到了问题。这是我的路线:

const routes: Routes = [

    { path: 'feed', loadChildren: './feed/feed.module#FeedModule', canLoad: [AuthGuardService] },
    { path: 'login', component: LoginPage },
    { path: 'register', component: RegisterPage },
    { path: '', redirectTo: '/feed', pathMatch: 'full' },
    { path: '**', redirectTo: '/' }
];

我的 AuthGuardService 有一个方法 canLoad,它总是返回 false 并重定向到 '/login' 路径:

...
@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
  canLoad(route: Route): boolean {

    this.router.navigate([ '/login' ]);
    return false;
  }
}

当我转到“localhost:4200/feed”时,我被重定向到“/login”。

但如果我转到 'localhost:4200/',则忽略身份验证保护并显示我的提要模块的组件。

你知道为什么吗?

谢谢!

【问题讨论】:

  • canLoad改成canActivate能用吗?

标签: angular angular-routing auth-guard


【解决方案1】:

我的场景中有一个工作代码。检查一下,如果它可以帮助你。

您可以使用 canActivate 来代替 canLoad。

canActivate 用于阻止未经授权的用户
canLoad 用于阻止应用的整个模块

在下面的示例中,如果您希望使用 canLoad 代替,可以将 canActivate 替换为 canLoad

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

在编写路线时,您可以如下定义。

{ path: 'newLeaveRequest', component: NewLeaveRequestComponent, canActivate: [AuthGuard]},
{ path: 'pastLeaveRequests', component: PastLeaveRequestComponent, canActivate: [AuthGuard]},

在 app.module.ts 中 在提供者中定义 AuthGuard。

【讨论】:

  • 感谢 anwser,但我将我的应用程序划分为不同的模块(如仪表板、newfeed 等),我真的想使用我的身份验证保护来防止 angular 加载完整模块并重定向到登录页面!如果您查看有关 canLoad 的角度文档,构造函数仅使用路由:angular.io/api/router/CanLoad 我已经尝试过使用 canActivate 并使用组件而不是模块的示例,它工作得很好。我不明白为什么在这里,我的空路径在 feed 上重定向但绕过身份验证保护
【解决方案2】:

我的问题已经解决了,抱歉耽搁了: 我需要使用一个组件并使用 canActivate 来加载子模块

{
    path: 'feed',
    canActivate: [ AuthGuard ],
    component: FeedComponent,
    children: [
        {
      path: '',
      loadChildren: () => FeedModule
}]}

对儿童的延迟加载也有效!

干杯!

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2019-03-15
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多