我如何设置 auth guard 只允许管理员使用管理仪表板(ngx-admin)?
How can i setup auth guard to only allow admins to use the admin dashboard(ngx-admin)?
我在 MySql 中有一个用户列表,每个用户的角色列要么是 ADMIN,要么是 USER。我已将 auth guard 设置为仅允许注册用户使用 ngx-admin,但我想更进一步,只允许管理员进入。我该怎么做?
关于授权。当角色不是管理员时,您必须发送未经授权的 API 响应。
然后你需要一个拦截器,它会在收到未授权响应时注销用户。或者可能 return 他到一个新的未经授权的页面。什么是首选。
我不知道spring。但是在angular中你可以这样修改拦截器。
@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);
}));
}
}
我在 MySql 中有一个用户列表,每个用户的角色列要么是 ADMIN,要么是 USER。我已将 auth guard 设置为仅允许注册用户使用 ngx-admin,但我想更进一步,只允许管理员进入。我该怎么做?
关于授权。当角色不是管理员时,您必须发送未经授权的 API 响应。
然后你需要一个拦截器,它会在收到未授权响应时注销用户。或者可能 return 他到一个新的未经授权的页面。什么是首选。
我不知道spring。但是在angular中你可以这样修改拦截器。
@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);
}));
}
}