gpt4 book ai didi

javascript - Angular 2 : AuthGard renders the page before it checks whether SecurityContext is applied or not

转载 作者:行者123 更新时间:2023-12-01 03:28:49 25 4
gpt4 key购买 nike

我正在使用 Angular,并尝试在某些路径上应用一些 AuthGard。

问题是 canActivate() 在检查 SecurityContext 之前呈现内容,在验证没有应用 SecurityContext 之后,会应用重定向到默认页面(登录)页面。

这是负责此操作的代码部分。

<小时/>

app.routing.ts

    {
path: 'admin',
canActivate: [AuthGard],
component: HomeComponent,
children : [
{
path: 'add-merchant-admin',
component : AddMerchantAdminComponent,
},
{
path: 'list-merchant-admin',
component : ListMerchantAdminComponent,
}
]
},
<小时/>

AuthGard.ts

  canActivate(_route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this._authService.getRoles().subscribe(
res => {
if (res.status == 200) {
this.roles = JSON.parse(res.text());
this.role = this.roles[0].authority;
localStorage.setItem('role', this.role);
if (this.role == 'ROLE_ADMIN') {
this._router.navigate(['admin']);
} else {
if (this.role == 'ROLE_ANONYMOUS') {
this._router.navigate(['login']);
this.error = false;
}
}
} else {
this._router.navigate(['login']);
this.error = true;
}
}, err => {
this._router.navigate(['login']);
this.error = true;
}
);
return !this.error;
};
<小时/>

AuthService

  getRoles() {
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers, withCredentials: true});
return this.http.get('http://10.0.0.239:8080/**/**/RolesResource/getRole', options)
.map((res) => res)
.catch((error: any) => Observable.throw(error.text() || 'Server error'));
}

所有服务均已正确注入(inject),通常,在使用 getRole() 方法进行验证后,应应用重定向到 protected 区域或默认页面。

最佳答案

您遇到的问题是 this._authService.getRoles() 进行异步网络调用。 return !this.error; 在网络调用返回之前被触发,因此 !this.error 不会改变,因此仍然是 true。

要解决此问题,您应该能够返回一个可观察对象,如下所示:

return this._authService.getRoles().map(
res => {
if (res.status == 200) {
this.roles = JSON.parse(res.text());
this.role = this.roles[0].authority;
localStorage.setItem('role', this.role);
if (this.role == 'ROLE_ADMIN') {
this._router.navigate(['admin']);
} else {
if (this.role == 'ROLE_ANONYMOUS') {
this._router.navigate(['login']);
return false;
}
}
} else {
this._router.navigate(['login']);
return true;
}
}).catch((err) => {
this._router.navigate(['login']);
return Observable.of(false);
}
);

关于javascript - Angular 2 : AuthGard renders the page before it checks whether SecurityContext is applied or not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648483/

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