我在MySql中有一个用户列表,每个用户都有一个角色列,即ADMIN或USER。我设置了auth防护,仅允许注册用户使用ngx-admin,但我想更进一步,仅允许管理员输入。我该怎么办?
答案 0 :(得分:0)
授权时。如果角色不是管理员,则必须发送未经授权的API响应。
然后,您需要一个拦截器,该拦截器将在收到未授权的响应时注销用户。或将他带回到新的未授权页面。首选。
我不懂春天。但是在角度上,您可以像这样修改拦截器。
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({ url: `${request.url}` });
// Sample how authorization headers are being assigned
let currentUser = this.authService.currentUserValue;
if (currentUser && currentUser.Token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.Token}`
}
});
}
////
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
}
return event;
}),
catchError((error: HttpErrorResponse) => {
//Here you can catch errors in the request.
if (error.status === 401) { <- 401 is UnAuthorized . if Status is 401
// auto logout if 401 response returned from api - Unauthorized
this.authService.logout();
location.reload(true);
//Redirecting is left to the AuthGuard. it will auto redirect on reload
}
//this is if any other error occurs.
let data = {};
data = {
reason: error && error.error.reason ? error.error.reason : '',
status: error.status
};
return throwError(error);
}));
}
}