我找到了另一种实现动作防护的方法。它是拦截器。当操作在没有有效令牌或没有必要数据的情况下向服务器发送请求时,服务器返回 401 或 403,具体取决于您的设置
@Injectable()
export class HttpAuthInterceptor {
constructor(
private toasterService: ToasterService,
private auth: AuthService,
private dialog: MatDialog) { }
public intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${this.auth.token}`
}
});
return next.handle(request)
.pipe(catchError(error => {
if (error instanceof HttpErrorResponse) {
switch (error.status) {
case 401:
this.auth.logout(request.urlWithParams);
this.dialog.closeAll();
break;
case 403:
this.dialog.closeAll();
this.dialog.open(ConfirmDialogComponent, {
autoFocus: false,
width: '65rem',
maxHeight: '95vh',
maxWidth: '80vw',
panelClass: 'confirme__dialog',
data: {
title: 'CONFIRM_DIALOG.TITLE',
text: 'CONFIRM_DIALOG.TEXT',
onConfirm: () => {
this.auth.logout(request.urlWithParams)
}
}
});
break;
case 0:
this.toasterService.error(error.message, {
duration: 5000,
});
break;
default:
this.toasterService.error(error.error.Message, {
duration: 5000,
});
}
}
return throwError(error);
}));
}
}