gpt4 book ai didi

Angular 6 : Guard on all routes is not working

转载 作者:行者123 更新时间:2023-12-02 08:04:26 26 4
gpt4 key购买 nike

我试图通过只允许某些 Id 获得访问权限来确保前端安全。我希望如果有人尝试输入除 /login/:id 之外的任何路由,如果他还没有登录,他将得到 page-not-found,但它不起作用。

这些是我的路由表和守卫:

编辑:我解决了问题并更新了代码:

app-routing.module.ts

// Routing array - set routes to each html page
const appRoutes: Routes = [{
path: 'login/:id',
canActivate: [AuthGuard],
children: []
},
{
path: '',
canActivate: [AuthGuard],
canActivateChild: [AuthGuard],
children: [{
path: '',
redirectTo: '/courses',
pathMatch: 'full'
},
{
path: 'courses',
component: CourseListComponent,
pathMatch: 'full'
},
{
path: 'courses/:courseId',
component: CourseDetailComponent,
pathMatch: 'full'
},
{
path: 'courses/:courseId/unit/:unitId',
component: CoursePlayComponent,
children: [{
path: '',
component: CourseListComponent
},
{
path: 'lesson/:lessonId',
component: CourseLessonComponent,
data: {
type: 'lesson'
}
},
{
path: 'quiz/:quizId',
component: CourseQuizComponent,
data: {
type: 'quiz'
}
}
]
}
]
},
{
path: '**',
component: PageNotFoundComponent,
pathMatch: 'full'
}
];

auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
// save the id from route snapshot
const id = +route.params.id;

// if you try to logging with id
if (id) {
this.authUserService.login(id);

// if there was error - return false
if (this.authUserService.errorMessage) {
this.router.navigate(["/page_not_found"]);
return false;
}

// there wasn't any errors - redirectTo courses and
// continue
else {
this.router.navigate(["courses"]);
return true;
}
}

// if you already logged and just navigate between pages
else if (this.authUserService.isLoggedIn())
return true;

else {
this.router.navigate(["/page_not_found"]);
return false;
}
}

canActivateChild(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
return this.canActivate(route, state);
}

auth-user.service.ts

export class AuthUserService implements OnDestroy {

private user: IUser;
public errorMessage: string;
isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

constructor(private userService: UserService) {}

// store the session and call http get
login(id: number) {
this.userService.getUser(id).subscribe(
user => {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));

localStorage.setItem('token', 'JWT');
this.isLoginSubject.next(true);
},
error => this.errorMessage = <any>error
);
}

// if we have token the user is loggedIn
// @returns {boolean}
private hasToken(): boolean {
return !!localStorage.getItem('token');
}

// @returns {Observable<T>}
isLoggedIn(): Observable<boolean> {
return this.isLoginSubject.asObservable();
}

// clear sessions when closing the window
logout() {
localStorage.removeItem('user');
localStorage.removeItem('token');
this.isLoginSubject.next(false);
}

ngOnDestroy() {
this.logout();
}

最佳答案

所以我设法解决了这个问题。我添加到 login/:id children: [] 的路由并将 isLoggedIn 更改为 behaviorSubject,因此 token 在刷新或在页面之间移动后不会更改并且它有效。我更新了帖子中的代码,以便每个人都可以看到解决方案

关于 Angular 6 : Guard on all routes is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com