我正在尝试在访问路由之前在后端验证令牌
这是我的身份验证服务:
export class AuthService {
private registerUrl = 'http://127.0.0.1:3000/register';
private loginUrl = 'http://127.0.0.1:3000/signin';
private verifyTokenUrl = 'http://127.0.0.1:3000/v';
constructor(private http: HttpClient) { }
isLoggedIn() {
if (!localStorage.getItem('token')) {
console.log('false in isloggedin method');
return false;
}
console.log('logged in, not verified yet');
return true;
}
isTokenValid(token): Observable<boolean> {
console.log('verifing');
return this.http.post<any>(this.verifyTokenUrl, {token});
}
getToken() {
return localStorage.getItem('token');
}
}
后卫:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
if (this.authService.isLoggedIn()) {
const token = localStorage.getItem('token');
this.authService.isTokenValid(token)
.pipe(
map(e => {
if (e) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}),
catchError((err) => {
this.router.navigate(['/login']);
return of(false);
})
);
} else {
this.router.navigate(['/login']);
return of(false);
}
}
}
似乎可观察对象不会“像使用订阅方法时一样”激活,并且API中的代码甚至都没有运行。 canActivate()假设接受一个Observable作为返回值。守卫将等待Observable解析并查看该值。如果为“ true”,它将通过检查,否则(任何其他数据或抛出错误)将拒绝该路由。引用此answer
在我的情况下,该应用程序停留在当前页面,并且不会路由到目标,也不会发布到服务器。还有一个类似的问题here,他们通过添加.take(1)
来解决,但在我的情况下,它给出了一个错误Property 'take' does not exist on type 'OperatorFunction<{}, boolean>'
这是我的验证API,以防万一
//.........token verify
app.post('/v', (req, res) => {
const {token} = req.body
const payload = jwt.verify(token, 'secretKey' )
console.log(payload);
if (!payload) {
return res.status(401).send(false)
}
res.status(200).send(true)
})
答案 0 :(得分:2)
您没有返回可观察到的信息:
this.authService.isTokenValid(token)
//...
—>
return this.authService.isTokenValid(token)
//...
答案 1 :(得分:1)
尝试实现您的路线后卫返回一个可观察的东西:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return Observable.create(observer => {
if (this.authService.isLoggedIn()) {
const token = localStorage.getItem('token');
this.authService.isTokenValid(token)
.pipe(
map(e => {
if (e) {
observer.next(true);
} else {
this.router.navigate(['/login']);
observer.next(false);
}
}),
catchError((err) => {
this.router.navigate(['/login']);
observer.next(false);
})
);
} else {
this.router.navigate(['/login']);
observer.next(false);
}
});
}
}
此外,别忘了在应用程序模块中将拦截器实现为提供程序:
// your.module.ts
// ...
providers: [
...,
AuthGuard
];
在您要守护的路线上:
// some route to guard
{ path: 'guarded-route', component: GuardedRouteComponent, canActivate: [AuthGuard] }