There is no AuthGaurd because everything auth related is handlend as interceptor. Should be less than a few lines to write one.
The interceptor checks if the backend call fails and then redirects to login. There are situations where we are loading a page without any backend calls. These are the dumb components that get loaded and when the user clicks on some button, the first backend call takes place, which then triggers the authentication logic through the interceptor.
Now if someone bookmarks a page or knows the urls, they are still able to load the page without having any authorisation to do so.
Which is why there is a need for auth guard.
I tried to call the app-state logic as an authguard which is provided in the supersonic template. This logic gets triggered only after the app component is loaded, which actually happens after the canActivate logic in the route. So i got errors.
I think what I mean is that we need a isAuthenticated boolean somewhere :-)
Did you mean there are a few lines of code which can handle this logic? Please elaborate.
Here is an "advanced" example of using an auth guard.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
let newState: State = INITSTATE;
return this.authService.session()
.pipe(
switchMap(resp => {
if (resp.ok) {
return this.userService.getUser();
}
return throwError("Forbidden");
}),
catchError(error => {
if (error.status == 500) {
this.authService.startLogout();
} else if (error.status == 401) {
this.authService.startLogin();
}
return throwError(error);
}), ........
// more code here
// auth service can look something like this
session(): Observable<HttpResponse<string>>{
return this.http.get<string>("/api/auth/session", {observe: 'response'})
}
startLogout(): void {
window.open("/api/auth/sso-logout", '_self');
}
startLogin(): void {
let next = location.pathname;
window.open("/api/auth/login" + next, '_self');
}
// on the backend side for example:
@GET
@PermitAll
@Path("/session")
public Response session(@Context SecurityContext ctx) {
if (ctx.getUserPrincipal() == null) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
return Response.status(Response.Status.OK).build();
}
This code ist taken from an active project an needs to be adjusted to your needs :)
Thank you. This is what I was looking for. I needed to know what to check at the backend. SecurityContext was the answer :-)