Logout feature with Spring Security and Navigator

I simply want to logout from my app.
Through research I came down to the following code for doing so:

Button logout = new Button("Logout"); logout.addClickListener(event1 -> {
SecurityContextHolder.clearContext();
UI.getCurrent().getNavigator().navigateTo(ViewNames.LOGIN);
});

It behaves as expected. But, n most cases I saw examples that use either UI.getCurrent.close() or UI.getCurrent().getSession().close().
When using the first, UI closes and when I return to the ‘login’ view, Fields for username and password are grayed out.
And when using Session.close(), it gives me ‘Session expired’ message.

Is it ok to leave my code as is for a clean ‘logout’ action or i need in some way to clear the session or the UI and restart them?

clearContext do not scrap application session nor vaadin session. Vaadin keeps component states in application’s session, if you haven’t protected unauthenticated user from accessing vaadin views, information from previous session may leak to next user.

Try something like

SecurityContextHolder.clearContext();
getUI().getSession().close();
Page.setLocation(...);  // navigate to login page

And check out
https://vaadin.com/api/com/vaadin/server/VaadinSession.html#close()

I found solution which seems to be behaving ok.
This is through Spring Security’s logout URL: “j_spring_security_logout”

logout.addClickListener(event1 -> {
SecurityContextHolder.clearContext();
Page.getCurrent().open("j_spring_security_logout", null);
});

Even so, I tried your reccomendation. But when I close the session I get exception:

javax.servlet.ServletException: com.vaadin.server.ServiceException: java.lang.RuntimeException: The given connector with id 3 is not the one that was registered for that id

I don’t know if it rings a bell.

Thanks for reply anyway