Vaadin 14 Authentication Handler

Hi,

I’ve been using older vaadin versions but just decided to give a shot at Vaadin 14 with SpringBoot for a new project and I’m trying to create a basic flow for protected routes and I don’t really manage to find a way to make it simple.

What I’d like to achieve is basically that if the user is not logged in and tries to access a view that is not LoginView.class, then the user is rerouted to LoginView.class. If the user is logged in, the filter should pass through.

I found that I can implement the BeforeEnterObserver on each route but it’s not scalable and I’d be placing the same logic everywhere. So, looking up at the [documentation]
(https://vaadin.com/docs/flow/routing/tutorial-routing-exception-handling.html) I found that there’s an example of AuthenticationHandler. I slightly tweaked it with rerouteTo("login"), but my biggest concern is that the method BeforeEnter is never called, so I guess that I should register this AuthenticationHandler somewhere. I also attempted to make it a Spring service with @UIScope and @SpringComponent.

@Setter
@Getter
@SessionScope
@Component
public class User {
    String username;
    String authToken;
    Boolean isLoggedIn = false;
}

For testing purposes, the LoginView sets the username and the isLoggedIn to true;

To check authentication I check if the isLoggedIn flag.

@Slf4j
@UIScope
@Service
public class AuthenticationHandler
        implements BeforeEnterObserver {

    @Autowired
    User user;

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        log.warn("Detected a routing event");
        Class<?> target = event.getNavigationTarget();
        if (!currentUserMayEnter(target, user)) {
            event.rerouteTo("login");
        }
    }

    private boolean currentUserMayEnter(
            Class<?> target, User user) {
        return user.getIsLoggedIn() && target.getSimpleName().equals("LoginView");
    }
}

Also, if I make my View implement the BeforeEventObserver my component will already be created and some external dependencies will be fetched. As the user might not already be logged in my service layer will make innecessary requests that will return a 401.

Long story short, just wondering how I can intercept the navigation before the view is created.

Regards,
Alex