Unanswered
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 :)
390 Views
0
Answers
2 years ago
2 years ago
Thank you. This is what I was looking for. I needed to know what to check at the backend. SecurityContext was the answer :-)