“Sometimes (or more), It's worth reinventing the wheel.”
Why? Link to heading
I am a follower of Vaadin , a very nice web development frameworks for Java Developers. With Vaadin, you can launch a web application written purely in Java. It’s somehow similar to the combination of JavaScript Frameworks and NodeJs in the Js World.
Recently, I start a new project using Vaadin and play around with setting the security configuration using Vaadin + Spring Boot + Spring Security: Enable Security. Things are working well until I see that the usage of built-in LoginForm in Vaadin is limited and hard to customize. That’s when I decided to implement a login page on my own for being able to add more features to the login screen and completely take control of it.
What I did? Link to heading
To test the concept, I built a simple button to test the manual login codes which will execute this code
var testUser = User.withUsername("user").password("{noop}user").roles("USER").build();
var authToken = new UsernamePasswordAuthenticationToken(testUser, null, AuthorityUtils.NO_AUTHORITIES);
SecurityContextHolder.getContext()setAuthentication(authToken);
getUI().ifPresent(ui -> ui.navigate("/protected-page"));
The codes I use should work well in a normal Spring Boot Web App.
I tried it and on the first test, it looks good. I login and is redirected to the link /protected-page successfully. But, guess what? When I refresh the page, I am redirected back to the login page. The security context is somehow vanished from the current session :(
The solution comes Link to heading
After several hours researching, I figure out that the way Vaadin handle the session is different from traditional web application (of course). Therefore, in order to persist the security context to the current user session, I have to do one more step:
var testUser = User.withUsername("user").password("{noop}user").roles("USER").build();
var authToken = new UsernamePasswordAuthenticationToken(testUser, null, AuthorityUtils.NO_AUTHORITIES);
// CHANGE LINES
var context = SecurityContextHolder.getContext();
context.setAuthentication(authToken);
VaadinRequest.getCurrent().getWrappedSession()
.setAttribute("SPRING_SECURITY_CONTEXT", context);
// ./CHANGE LINES
getUI().ifPresent(ui -> ui.navigate("/protected-page"));
Now it works as I expected: I can reload the protected pages and still stay on it until I log out of the app.
Keep calm and good things will come!
Subscribe to our newsletter • About the author