I store my session in database, I have columns with user id, UUID and expiration date. Before any request from Angular I would like to send request to the method in api which check expiration date and let angular send another request if is valid or logout user and remove local storage with token with message about expiration date of my session. I'm looking for similar solution to HTTPInterceptor which add headers automatically to every request instead of add headers to any method with request before.
I'm using Angular 10 and Spring Boot 2.3.1.
EDIT.
I found the solution for catching errors in any request in my interceptor on the Angular side.
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (localStorage.getItem('username') && localStorage.getItem('basicauth')) {
req = req.clone({
setHeaders: {
Authorization: localStorage.getItem('basicauth')
}
})
}
return next.handle(req).pipe(
catchError(response => {
console.log(response.status)
// do something, example clear LocalStorage...
return throwError(response);
})
)
}
}
EDIT 2.
I made Interceptor with preHandle()
method in Spring-Boot to check session expiration date before request and if session is expired I set unique response status to 495
which tell Angular to logout the user and clear LocalStorage
.
preHandle() method in Spring-Boot:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//if (request.getRequestURL().toString().endsWith("/api/basicauth"))
String GUID = request.getHeader("GUID") == null? "1" : request.getHeader("GUID");
if (sessionService.getSessionByGuid(GUID).isPresent()) {
Session session = sessionService.getSessionByGuid(GUID).get();
if(session.getExpirationDate().isBefore(LocalDateTime.now())) {
sessionService.deleteSession(GUID);
response.setStatus(495);
return false;
} else {
sessionService.renewSession(session);
return true;
}
}
return true;
}
Interceptor method in Angular:
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (localStorage.getItem('username') && localStorage.getItem('basicauth')) {
req = req.clone({
setHeaders: {
Authorization: localStorage.getItem('basicauth'),
GUID: localStorage.getItem('GUID')
}
})
}
return next.handle(req).pipe(
catchError(response => {
if (response.status == 495) {
this.auth.removeSessionAndStorage();
this.openSnackBar("Twoja sesja wygasłą!",);
this.router.navigate(['login', 'session-expired']);
}
return throwError(response);
})
);
}