I have a list of users in MySql, Each one has role column that is either ADMIN or USER. I have setup auth guard to only allow a registered user to use the ngx-admin but I want to take a step further and only allow the admin to enter. How can i do that?
Asked
Active
Viewed 224 times
-1
-
If you are authorizing from the API. you can just return the user to the login page if you get an unauthorized response from the api (you can do that in the interceptor) – zetawars May 02 '19 at 11:47
-
Sorry but can you explain to me more how I can do that? Btw, I'm using spring as backend – user10976183 May 02 '19 at 11:53
1 Answers
1
On Authorization. You have to send an Unauthorized API Response when the Role is not Admin.
Then you need an interceptor which will logout the user when unauthorize response is received. or maybe return him to a new unauthorized page. whatever is preferred.
I have no knowledge of spring. But in angular you can modify the interceptor like this.
@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);
}));
}
}