Skip to content
javahacks.dev
Vaadin

Vaadin Spring Security Setup to Secure a Flow Application

Secure a Vaadin Flow application with Spring Security: the VaadinWebSecurity base, a login view, view access annotations and logout, with form login.

6 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security, OWASP and Keycloak logos.

Vaadin Flow runs your UI on the server, so Spring Security protects it with the same session mechanism as any other web application. What is different is Vaadin's own traffic: bundle files, UI requests and push connections that a naive security configuration would block. A base class from the Vaadin integration handles those, and the remaining work is to define users, a login view and access rules on views. This guide covers all of that for Vaadin 25 with Spring Boot 4, and explains why the security rules also belong in the service layer. The framework basics are in Vaadin with Spring Boot.

The security configuration

java
@EnableWebSecurity
@Configuration
class SecurityConfig extends VaadinWebSecurity {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth ->
                auth.requestMatchers("/public/**").permitAll());
        super.configure(http);
        setLoginView(http, LoginView.class);
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("ada").password(encoder.encode("change-me")).roles("USER").build(),
            User.withUsername("root").password(encoder.encode("change-me-too")).roles("ADMIN").build());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

VaadinWebSecurity permits Vaadin's internal endpoints (bundle files, the UI request path, icons), configures CSRF in a form that suits Vaadin and sets the default access policy. Call super.configure(http) after your own matchers, and setLoginView last. The in-memory users exist only to make the example run; use a database-backed UserDetailsService in a real application, and never keep passwords in source. The delegating encoder stores a prefix such as {bcrypt} with each hash, so you can change the algorithm later without invalidating existing passwords. The same user model is explained in Java security basics.

The login view

java
@Route("login")
@PageTitle("Sign in")
@AnonymousAllowed
class LoginView extends VerticalLayout implements BeforeEnterObserver {

    private final LoginForm login = new LoginForm();

    LoginView() {
        login.setAction("login");
        setAlignItems(Alignment.CENTER);
        add(new H1("Orders"), login);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        if (event.getLocation().getQueryParameters().getParameters().containsKey("error")) {
            login.setError(true);
        }
    }
}

The form posts to /login, and Spring Security authenticates it. On failure Spring redirects to /login?error, and the observer turns on the error message. The route needs @AnonymousAllowed, or nobody could reach the page that lets them sign in, a mistake that shows up as a redirect loop.

Protect the views

java
@Route("orders")
@PermitAll
class OrdersView extends VerticalLayout { /* ... */ }

@Route("admin")
@RolesAllowed("ADMIN")
class AdminView extends VerticalLayout { /* ... */ }
AnnotationWho may enter
@AnonymousAllowedEveryone, including signed-out users
@PermitAllAny signed-in user
@RolesAllowed("X")Users with role X
@DenyAllNo one (the default if nothing is annotated)

A view without an annotation is denied, which is the safe default and also the cause of "route not found" surprises when you add a new view and forget the annotation. A user who lacks access is shown the same not-found response as a missing route, so the existence of an admin page is not revealed.

Logout and the current user

java
@Autowired AuthenticationContext authContext;

Button logout = new Button("Log out", e -> authContext.logout());
String name = authContext.getPrincipalName().orElse("anonymous");

AuthenticationContext is a Spring bean provided by the integration, and it hides the details of reading the security context from the Vaadin session. Showing or hiding a button according to a role is a convenience for the user. It is never protection, because the server must decide independently.

Security belongs in the service layer too

A Vaadin UI could be bypassed by anyone who calls the server directly, so enforce the rules where the data is.

java
@Service
class OrderService {

    @PreAuthorize("hasRole('ADMIN')")
    public void delete(long id) { /* ... */ }
}

Enable it with @EnableMethodSecurity. A user who guesses the view URL is stopped by the view annotation, and one who finds another route in, such as a scheduled job or a second UI, is stopped by the service. Test both layers: a view test with a user lacking the role, and a service test that calls the method as that user and expects an access denied exception. For the failure responses a browser sees, read 403 Forbidden.

Sessions and persistent logins

Vaadin keeps UI state in the HTTP session, so the session timeout decides how long a user can leave a tab idle. Set it deliberately in server.servlet.session.timeout, and decide whether a persistent login is acceptable for your risk. When the session expires, Vaadin shows a session-expired notice; configure it to take users to the login view. Behind a load balancer, either use sticky sessions or share sessions in a store, otherwise a request on another node sees a different, unauthenticated session.

Testing the access rules

Write a test per annotated view. Spring's @WithMockUser(roles = "USER") and @WithAnonymousUser give the security context, and a browser-free test can navigate to the route and assert whether the view or the login redirect is shown. A short matrix of role against view, kept as a parameterised test, catches the change that makes an admin page open to everyone. Also test the login view with a wrong password and confirm the error text is generic, so it does not reveal whether the user exists.

Public pages and static resources

Not every route needs a login. A landing page, a health check and a public status view belong behind @AnonymousAllowed, and static files under /public/** or /images/** are permitted by the matcher in the configuration above. Keep the list short and review it when adding routes. Actuator endpoints deserve their own rules: expose /actuator/health to the load balancer, and restrict the rest to an administrator role or an internal network. A permissive default combined with a forgotten matcher is how internal endpoints end up on the internet.

CSRF and Vaadin

The integration keeps CSRF protection on for Vaadin's own requests, using a token that the client library sends automatically, so you do not write any code for it. Custom endpoints you add outside Vaadin, such as a webhook, are different: they receive requests from systems that do not carry the token. Exclude exactly those paths from CSRF with csrf.ignoringRequestMatchers("/webhooks/**"), authenticate them with a signature or a token of their own, and leave CSRF on for everything else.

Auditing sign-ins

Log successful and failed logins with the username and the source address, and alert on a burst of failures for one account. Spring Security publishes authentication events that you can listen to with an @EventListener, so no changes to the login flow are needed.

Embedding the login in a layout

If the application has a main layout with a menu, hide the menu for the login route so signed-out users see only the form. Use the same @AnonymousAllowed rule, and redirect signed-in users away from the login page. A user who bookmarks a protected view should land on it after signing in, which the integration supports by remembering the requested location. Test that flow once with a real browser, because it involves a redirect and a session cookie.

When to change the approach

For OIDC single sign-on, replace the form login with oauth2Login() and keep the rest, including the view annotations. Hilla applications use the same base class. The reference is the Vaadin security documentation, and the Spring Security reference covers the underlying features. The wider guide to the framework is Vaadin web UIs.

Also inSecurity
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.