我正在尝试阻止非管理员用户访问管理仪表板本身。为此,我必须在后端检查令牌是否有效,如果有效,则确认用户实际上是管理员。我似乎能够阻止它,但我不知道如何等待在Angular 11的AuthGuard中的API调用?我必须让canActivate()方法异步吗?
AuthenticationService:
// This method works and returns an Observable<boolean>
public hasUserRole(theAccessToken: string, userRole: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
accessToken: theAccessToken,
requiredUserRole: userRole,
})
};
return this.http.get<any>(Constants.API_ENDPOINT_GET_USER_ROLES, httpOptions);
}
// This method, I don't know how to implement... I tried .pipe and .tap and whatnot but I can't get anything to wait for the API call to finish.
public isLoggedInAndHasUserRole(token: string, userRole: string): boolean {
// return this.hasUserRole(token, userRole); // TODO: How to wait for this API call? .map doesn't seem to work in Angular11 and I can't get the .pipe() to work either.
}Auth Guard (可以工作,但我不知道如何等待API调用):
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const token = this.commonService.getToken();
if (token !== '' && token !== undefined) {
if (this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin')) {
<snip for brevity>包含API结果的图像

发布于 2021-02-01 03:01:55
canActivate has several return values.您可以返回Observable<boolean>,只有在解析了该可观察对象之后,身份验证保护才会继续。
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
const token = this.commonService.getToken();
if (token !== '' && token !== undefined) {
return this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin').pipe(
map((hasRole) => {
if (hasRole) {
return true;
} else {
this.commonService.navigateToHome();
return false; //
}
}));
} else {
this.commonService.navigateToLogin();
return false;
}
}在您的授权服务中:
public isLoggedInAndHasUserRole(token: string, userRole: string): Observable<boolean> {
return this.hasUserRole(token, userRole);
}https://stackoverflow.com/questions/65982975
复制相似问题