Documentation versions (currently viewingVaadin 23)

You are viewing documentation for Vaadin 23. View latest documentation

Adding a Login Screen to a Vaadin Application Using Spring Security

Learn to set up Spring Security to restrict access to views in a Flow application.

In this chapter, you secure the Customer Relationship Management (CRM) application by setting up Spring Security and adding a login screen to limit access to logged-in users.

Creating a Login View

Start by creating a new view, LoginView, in the views package.

package com.example.application.views;

import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;

@Route("login") // (1)
@PageTitle("Login | Vaadin CRM")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {

	private final LoginForm login = new LoginForm(); // (2)

	public LoginView(){
		setSizeFull(); // (3)

		login.setAction("login"); // (4)

		add(new H1("Vaadin CRM"), login);

	public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
		// inform the user about an authentication error
		if(beforeEnterEvent.getLocation()  // (5)
        .containsKey("error")) {
  1. Map the view to the "login" path. LoginView should take up the whole browser window, so don’t use MainLayout as the parent.

  2. Instantiate a LoginForm component to capture username and password.

  3. Make LoginView full size and center its content both horizontally and vertically, by calling setAlignItems(`Alignment.CENTER)` and setJustifyContentMode(`JustifyContentMode.CENTER)`.

  4. Set the LoginForm action to "login" to post the login form to Spring Security.

  5. Read query parameters and show an error if a login attempt fails.

Build the application and navigate to http://localhost:8080/login. You should see a centered login form.

Login view

Setting up Spring Security to Handle Logins

With the login screen in place, you now need to configure Spring Security to perform the authentication and to prevent unauthorized users from accessing views.

Installing Spring Security Dependencies

Add the Spring Security dependency in pom.xml:


Check that the dependency is downloaded. If you are unsure, run ./mvnw install from the command line to download the dependency.

Configuring Spring Security

Create a new package for classes related to security.

Create Classes Automatically

Paste the class code into the security package to have IntelliJ automatically create the class for you.

Enable and configure Spring Security with a new class,


import java.util.Collections;

import com.example.application.views.LoginView;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@EnableWebSecurity // (1)
public class SecurityConfig extends VaadinWebSecurity { // (2)

     * Demo SimpleInMemoryUserDetailsManager, which only provides
     * two hardcoded in-memory users and their roles.
     * NOTE: This shouldn't be used in real-world applications.
    private static class SimpleInMemoryUserDetailsManager extends InMemoryUserDetailsManager {
        public SimpleInMemoryUserDetailsManager() {
            createUser(new User("user",
                Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))
            createUser(new User("admin",
                Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"))

    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/images/**").permitAll(); // (3)


        setLoginView(http, LoginView.class); // (4)

    public InMemoryUserDetailsManager userDetailsService() {
        return new SimpleInMemoryUserDetailsManager(); // (5)
  1. Enable Spring Security.

  2. Extend the VaadinWebSecurity class to configure Spring Security for Vaadin.

  3. Allow public access to the image directory.

  4. Allow access to LoginView.

  5. Configure an in-memory user for testing (see note below).

Never use hard-coded credentials in production

Don’t use hard-coded credentials in real applications. You can change the Spring Security configuration to use an authentication provider for Lightweight Directory Access Protocol (LDAP), Java Authentication and Authorization Service (JAAS), and other real-world sources. Read more about Spring Security authentication providers.

Then, in the same package, create a service for accessing information on the logged-in user and for logging the user out.


import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.VaadinServletRequest;
import org.springframework.stereotype.Component;

public class SecurityService {

    private static final String LOGOUT_SUCCESS_URL = "/";

    public UserDetails getAuthenticatedUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Object principal = context.getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return (UserDetails) principal;
        // Anonymous or no authentication.
        return null;

    public void logout() {
        SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
                VaadinServletRequest.getCurrent().getHttpServletRequest(), null,

Finally, add @PermitAll annotations to both views to allow all logged-in users to access them.

@Route(value="", layout = MainLayout.class)
@PageTitle("Contacts | Vaadin CRM")
public class ListView extends VerticalLayout {
    // omitted
@Route(value = "dashboard", layout = MainLayout.class)
@PageTitle("Dashboard | Vaadin CRM")
public class DashboardView extends VerticalLayout {
    // omitted

Adding a Logout Button

You can now log in to the application. The last item to add is a logout button in the application header.

In MainLayout, add a link to the header:

package com.example.application.views;

import com.example.application.views.list.ListView;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.HighlightConditions;
import com.vaadin.flow.router.RouterLink;

public class MainLayout extends AppLayout {
    private final SecurityService securityService;

    public MainLayout(SecurityService securityService) { // (1)
        this.securityService = securityService;

    private void createHeader() {
        H1 logo = new H1("Vaadin CRM");
        logo.addClassNames("text-l", "m-m");

        Button logout = new Button("Log out", e -> securityService.logout()); // (2)

        HorizontalLayout header = new HorizontalLayout(new DrawerToggle(), logo, logout); // (3)

        header.expand(logo); // (4)
        header.addClassNames("py-0", "px-m");



    private void createDrawer() {
        RouterLink listLink = new RouterLink("List", ListView.class);

        addToDrawer(new VerticalLayout(
            new RouterLink("Dashboard", DashboardView.class)
  1. Autowire the SecurityService and save it in a field.

  2. Create a logout button that calls the logout() method in the service.

  3. Add the button to the header layout.

  4. Call header.expand(logo) to make the logo take up all the extra space in the layout. This pushes the logout button to the far right.

Stop and restart the server to pick up the new Maven dependencies. You should now be able to log in and out of the app. Verify that you can’t access http://localhost:8080/dashboard without being logged in. You can log in with:

  • Username: user

  • Password: userpass

Log out button on page

You have now built a full-stack CRM application with navigation and authentication. In the next chapter, you learn how to turn it into a PWA to make it installable on mobile and desktop.

migration assistance

Download free e-book.
The complete guide is also available in an easy-to-follow PDF format.

Open in a
new tab
export class RenderBanner extends HTMLElement {
  connectedCallback() {

  renderBanner() {
    let bannerWrapper = document.getElementById('tocBanner');

    if (bannerWrapper) {

    let tocEl = document.getElementById('toc');

    // Add an empty ToC div in case page doesn't have one.
    if (!tocEl) {
      const pageTitle = document.querySelector(
        'main > article > header[class^=PageHeader-module--pageHeader]'
      tocEl = document.createElement('div');

      pageTitle?.insertAdjacentElement('afterend', tocEl);

    // Prepare banner container
    bannerWrapper = document.createElement('div'); = 'tocBanner';

    // Banner elements
    const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
    const link = document.querySelector('.toc-banner-source-link')?.textContent;

    const bannerHtml = `<div class='toc-banner'>
          <a href='${link}'>
            <div class="toc-banner--img"></div>
            <div class='toc-banner--content'>${text}</div>

    bannerWrapper.innerHTML = bannerHtml;

    // Add banner image
    const imgSource = document.querySelector('.toc-banner-source .image');
    const imgTarget = bannerWrapper.querySelector('.toc-banner--img');

    if (imgSource && imgTarget) {