Adding a Login Screen to a Vaadin Application Using Spring Security

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

Tip
Simplified Security

Vaadin 21 and later include built-in Spring Security helpers that greatly simplify securing your Flow application. You can follow the Vaadin 21 version of this tutorial if you prefer to use the helpers.

Creating a Login View

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

LoginView.java

  1. package com.example.application.views;
  2. import com.vaadin.flow.component.html.H1;
  3. import com.vaadin.flow.component.login.LoginForm;
  4. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  5. import com.vaadin.flow.router.BeforeEnterEvent;
  6. import com.vaadin.flow.router.BeforeEnterObserver;
  7. import com.vaadin.flow.router.PageTitle;
  8. import com.vaadin.flow.router.Route;
  9. @Route("login") 1
  10. @PageTitle("Login | Vaadin CRM")
  11. public class LoginView extends VerticalLayout implements BeforeEnterObserver {
  12. private final LoginForm login = new LoginForm(); 2
  13. public LoginView(){
  14. addClassName("login-view");
  15. setSizeFull(); 3
  16. setAlignItems(Alignment.CENTER);
  17. setJustifyContentMode(JustifyContentMode.CENTER);
  18. login.setAction("login"); 4
  19. add(new H1("Vaadin CRM"), login);
  20. }
  21. @Override
  22. public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
  23. // inform the user about an authentication error
  24. if(beforeEnterEvent.getLocation() 5
  25. .getQueryParameters()
  26. .getParameters()
  27. .containsKey("error")) {
  28. login.setError(true);
  29. }
  30. }
  31. }
  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/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:

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>

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

Next, disable Spring MVC auto-configuration on the Application class, as this interferes with how Vaadin works and can cause strange reloading behavior.

**Application.class**

  1. @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
  2. @NpmPackage(value = "lumo-css-framework", version = "^4.0.10")
  3. public class Application extends SpringBootServletInitializer {
  4. ...
  5. }

Configuring Spring Security

Create a new package com.example.application.security for classes related to security.

In the new package, create the following classes using the code detailed below:

  • SecurityUtils: utility methods.

  • CustomRequestCache: a cache to keep track of unauthenticated requests.

  • SecurityConfiguration: Spring Security configuration.

  • SecurityService: a service for getting information about the logged-in user and logging them out.

Tip
Create Classes Automatically

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

SecurityUtils.java

  1. package com.example.application.security;
  2. import com.vaadin.flow.server.HandlerHelper.RequestType;
  3. import com.vaadin.flow.shared.ApplicationConstants;
  4. import org.springframework.security.authentication.AnonymousAuthenticationToken;
  5. import org.springframework.security.core.Authentication;
  6. import org.springframework.security.core.context.SecurityContextHolder;
  7. import javax.servlet.http.HttpServletRequest;
  8. import java.util.stream.Stream;
  9. public final class SecurityUtils {
  10. private SecurityUtils() {
  11. // Util methods only
  12. }
  13. static boolean isFrameworkInternalRequest(HttpServletRequest request) { 1
  14. final String parameterValue = request.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER);
  15. return parameterValue != null
  16. && Stream.of(RequestType.values())
  17. .anyMatch(r -> r.getIdentifier().equals(parameterValue));
  18. }
  19. static boolean isUserLoggedIn() { 2
  20. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  21. return authentication != null
  22. && !(authentication instanceof AnonymousAuthenticationToken)
  23. && authentication.isAuthenticated();
  24. }
  25. }
  1. isFrameworkInternalRequest() determines if a request is internal to Vaadin.

  2. isUserLoggedIn() checks if the current user is logged in.

CustomRequestCache.java

  1. package com.example.application.security;
  2. import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. class CustomRequestCache extends HttpSessionRequestCache {
  6. @Override
  7. public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
  8. if (!SecurityUtils.isFrameworkInternalRequest(request)) {
  9. super.saveRequest(request, response); 1
  10. }
  11. }
  12. }
  1. Saves unauthenticated requests, so that, once the user is logged in, you can redirect them to the page they were trying to access.

SecurityConfig.java

  1. package com.example.application.security;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.core.userdetails.User;
  9. import org.springframework.security.core.userdetails.UserDetails;
  10. import org.springframework.security.core.userdetails.UserDetailsService;
  11. import org.springframework.security.provisioning.InMemoryUserDetailsManager;
  12. @EnableWebSecurity
  13. @Configuration
  14. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  15. private static final String LOGIN_PROCESSING_URL = "/login";
  16. private static final String LOGIN_FAILURE_URL = "/login?error";
  17. private static final String LOGIN_URL = "/login";
  18. private static final String LOGOUT_SUCCESS_URL = "/login";
  19. /**
  20. * Require login to access internal pages and configure login form.
  21. */
  22. @Override
  23. protected void configure(HttpSecurity http) throws Exception {
  24. // Vaadin handles CSRF internally
  25. http.csrf().disable()
  26. // Register our CustomRequestCache, which saves unauthorized access attempts, so the user is redirected after login.
  27. .requestCache().requestCache(new CustomRequestCache())
  28. // Restrict access to our application.
  29. .and().authorizeRequests()
  30. // Allow all Vaadin internal requests.
  31. .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
  32. // Allow all requests by logged-in users.
  33. .anyRequest().authenticated()
  34. // Configure the login page.
  35. .and().formLogin()
  36. .loginPage(LOGIN_URL).permitAll()
  37. .loginProcessingUrl(LOGIN_PROCESSING_URL)
  38. .failureUrl(LOGIN_FAILURE_URL)
  39. // Configure logout
  40. .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);
  41. }
  42. @Bean
  43. @Override
  44. public UserDetailsService userDetailsService() {
  45. UserDetails user = User.withUsername("user")
  46. .password("{noop}userpass")
  47. .roles("USER")
  48. .build();
  49. return new InMemoryUserDetailsManager(user);
  50. }
  51. /**
  52. * Allows access to static resources, bypassing Spring Security.
  53. */
  54. @Override
  55. public void configure(WebSecurity web) {
  56. web.ignoring().antMatchers(
  57. // Client-side JS
  58. "/VAADIN/**",
  59. // the standard favicon URI
  60. "/favicon.ico",
  61. // the robots exclusion standard
  62. "/robots.txt",
  63. // web application manifest
  64. "/manifest.webmanifest",
  65. "/sw.js",
  66. "/offline.html",
  67. // icons and images
  68. "/icons/**",
  69. "/images/**",
  70. "/styles/**",
  71. // (development mode) H2 debugging console
  72. "/h2-console/**");
  73. }
  74. }
Warning
Never use hard-coded credentials in production

Do not use hard-coded credentials in real applications. You can change the Spring Security configuration to use an authentication provider for LDAP, JAAS, and other real-world sources. Read more about Spring Security authentication providers.

Restricting Access to Vaadin Views

Spring Security restricts access to content based on paths. Vaadin applications are single-page applications. This means that they do not trigger a full browser refresh when you navigate between views, even though the path does change. To secure a Vaadin application, you need to wire Spring Security to the Vaadin navigation system.

To do this, create a new class in the security package, ConfigureUIServiceInitListener.java.

ConfigureUIServiceInitListener.java

  1. package com.example.application.security;
  2. import com.example.application.views.LoginView;
  3. import com.vaadin.flow.component.UI;
  4. import com.vaadin.flow.router.BeforeEnterEvent;
  5. import com.vaadin.flow.server.ServiceInitEvent;
  6. import com.vaadin.flow.server.VaadinServiceInitListener;
  7. import org.springframework.stereotype.Component;
  8. @Component 1
  9. public class ConfigureUIServiceInitListener implements VaadinServiceInitListener {
  10. @Override
  11. public void serviceInit(ServiceInitEvent event) { 2
  12. event.getSource().addUIInitListener(uiEvent -> {
  13. final UI ui = uiEvent.getUI();
  14. ui.addBeforeEnterListener(this::authenticateNavigation);
  15. });
  16. }
  17. private void authenticateNavigation(BeforeEnterEvent event) { 3
  18. if (!LoginView.class.equals(event.getNavigationTarget())
  19. && !SecurityUtils.isUserLoggedIn()) {
  20. event.rerouteTo(LoginView.class);
  21. }
  22. }
  23. }
  1. The @Component annotation registers the listener. Vaadin will pick it up on startup.

  2. In serviceInit(), listen for the initialization of the UI (the internal root component in Vaadin) and then add a listener before every view transition.

  3. In authenticateNavigation(), reroute all requests to the login, if the user is not logged in.

Finally, create a service for accessing user information and logging out. Create SecurityService.java in the security package.

SecurityService.java

  1. package com.example.application.security;
  2. import com.vaadin.flow.component.UI;
  3. import com.vaadin.flow.server.VaadinServletRequest;
  4. import org.springframework.security.core.context.SecurityContext;
  5. import org.springframework.security.core.context.SecurityContextHolder;
  6. import org.springframework.security.core.userdetails.UserDetails;
  7. import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
  8. import org.springframework.stereotype.Component;
  9. @Component
  10. public class SecurityService {
  11. private static final String LOGOUT_SUCCESS_URL = "/";
  12. public UserDetails getAuthenticatedUser() {
  13. SecurityContext context = SecurityContextHolder.getContext();
  14. Object principal = context.getAuthentication().getPrincipal();
  15. if (principal instanceof UserDetails) {
  16. return (UserDetails) context.getAuthentication().getPrincipal();
  17. }
  18. // Anonymous or no authentication.
  19. return null;
  20. }
  21. public void logout() {
  22. UI.getCurrent().getPage().setLocation(LOGOUT_SUCCESS_URL);
  23. SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
  24. logoutHandler.logout(
  25. VaadinServletRequest.getCurrent().getHttpServletRequest(), null,
  26. null);
  27. }
  28. }

Adding a Logout Button

You can now log in to the application. The final thing that is needed is a logout button in the application header.

In MainLayout, add a link to the header:

MainLayout.java

  1. package com.example.application.views;
  2. import com.example.application.security.SecurityService;
  3. import com.example.application.views.list.ListView;
  4. import com.vaadin.flow.component.applayout.AppLayout;
  5. import com.vaadin.flow.component.applayout.DrawerToggle;
  6. import com.vaadin.flow.component.button.Button;
  7. import com.vaadin.flow.component.html.H1;
  8. import com.vaadin.flow.component.orderedlayout.FlexComponent;
  9. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  10. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  11. import com.vaadin.flow.router.HighlightConditions;
  12. import com.vaadin.flow.router.RouterLink;
  13. import com.vaadin.flow.theme.Theme;
  14. @Theme(themeFolder = "flowcrmtutorial")
  15. public class MainLayout extends AppLayout {
  16. private final SecurityService securityService;
  17. public MainLayout(SecurityService securityService) { 1
  18. this.securityService = securityService;
  19. createHeader();
  20. createDrawer();
  21. }
  22. private void createHeader() {
  23. H1 logo = new H1("Vaadin CRM");
  24. logo.addClassNames("text-l", "m-m");
  25. Button logout = new Button("Log out", e -> securityService.logout()); 2
  26. HorizontalLayout header = new HorizontalLayout(new DrawerToggle(), logo, logout); 3
  27. header.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
  28. header.expand(logo); 4
  29. header.setWidth("100%");
  30. header.addClassNames("py-0", "px-m");
  31. addToNavbar(header);
  32. }
  33. private void createDrawer() {
  34. RouterLink listLink = new RouterLink("List", ListView.class);
  35. listLink.setHighlightCondition(HighlightConditions.sameLocation());
  36. addToDrawer(new VerticalLayout(
  37. listLink,
  38. new RouterLink("Dashboard", DashboardView.class)
  39. ));
  40. }
  41. }
  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/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’ll 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.

https://pages.vaadin.com/en/build-a-modern-web-app-with-spring-boot-vaadin-pdf

Open in anew tab

Show code

render-banner.ts

  1. export class RenderBanner extends HTMLElement {
  2. connectedCallback() {
  3. this.renderBanner();
  4. }
  5. renderBanner() {
  6. let bannerWrapper = document.getElementById('tocBanner');
  7. if (bannerWrapper) {
  8. return;
  9. }
  10. let tocEl = document.getElementById('toc');
  11. // Add an empty ToC div in case page doesn't have one.
  12. if (!tocEl) {
  13. const pageTitle = document.querySelector(
  14. 'main > article > header[class^=PageHeader-module--pageHeader]'
  15. );
  16. tocEl = document.createElement('div');
  17. tocEl.classList.add('toc');
  18. pageTitle?.insertAdjacentElement('afterend', tocEl);
  19. }
  20. // Prepare banner container
  21. bannerWrapper = document.createElement('div');
  22. bannerWrapper.id = 'tocBanner';
  23. tocEl?.appendChild(bannerWrapper);
  24. // Banner elements
  25. const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
  26. const link = document.querySelector('.toc-banner-source-link')?.textContent;
  27. const bannerHtml = `<div class='toc-banner'>
  28. <a href='${link}'>
  29. <div class="toc-banner--img"></div>
  30. <div class='toc-banner--content'>${text}</div>
  31. </a>
  32. </div>`;
  33. bannerWrapper.innerHTML = bannerHtml;
  34. // Add banner image
  35. const imgSource = document.querySelector('.toc-banner-source .image');
  36. const imgTarget = bannerWrapper.querySelector('.toc-banner--img');
  37. if (imgSource && imgTarget) {
  38. imgTarget.appendChild(imgSource);
  39. }
  40. }
  41. }