簡體   English   中英

我如何設置身份驗證保護以僅允許管理員使用管理儀表板(ngx-admin)?

[英]How can i setup auth guard to only allow admins to use the admin dashboard(ngx-admin)?

我在 MySql 中有一個用戶列表,每個用戶都有 ADMIN 或 USER 的角色列。 我已經設置了身份驗證保護,只允許注冊用戶使用 ngx-admin,但我想更進一步,只允許管理員進入。 我怎樣才能做到這一點?

關於授權。 當角色不是管理員時,您必須發送未經授權的 API 響應。

然后你需要一個攔截器,它會在收到未經授權的響應時注銷用戶。 或者讓他返回一個新的未經授權的頁面。 無論是首選。

我對春天一無所知。 但是在 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);
            }));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM