After rerouting to the `LoginForm`, how do I return to original route desir

On the @Route views of my Vaadin 14 app where I require the user to be authenticated (username/password), I am implementing BeforeEnterObserver and its beforeEnter method. In that method, if I detect the user has not yet been authenticated, I call rerouteTo on the BeforeEnterEvent object. I pass the .class of my authenticate-user view where I use the LoginForm widget provided by Vaadin 14.

But what should happen after the user authenticates? After my LoginEvent listener is invoked, and I retrieve the entered username and password, and verify those credentials, how do I return to the original view that rerouted to the login?

At first I thought of using History to go back. But what if my /login route happens to be the first one called in the session (perhaps from the user invoking a bookmark)? Well, then I thought I could see if the History trail was empty, then I could reroute to empty path "". But the History object does not show its history, does not let you interrogate the size of its collection of visited URLs. So I do not know if my /login view was the first URL visited or not.

How to resolve this conundrum?

One approach is that in your MainLayout, i.e. the root level RouterLayout you add BeforeEnterObserver, where you store the intended path e.g. in session attribute. Parent gets BeforeEnterEvent also when navigating to child views with url. Then you can use that path after successful login. Something like

@Override
public void beforeEnter(BeforeEnterEvent event) {
   if (userIsLoggedIn() == false) {
      VaadiSession.getCurrent().setAttribute("intentedPath", event.getLocation().getPath());
   }
}

End then in the login after successful login do

Object intetedPath = VaadinSession.getCurrent().getAttribute("intendedPath")
UI.getCurrent().navigate(Optional.ofNullable(intendedPath).map(Object::toString).orElse(""));

This is the rough idea.