Docs

Documentation versions (currently viewingVaadin 24)

Login & Logout

Creating login and logout controls using Control Center identity management security.

For users to login and logout, it’s useful to provide them with a link or button to do so. This page explains how to do that in a Vaadin application when using the Identity Management feature in Control Center.

Adding Login

To add a login link or button to a Vaadin application, you’ll need to create a component that redirects users to the login page provided by Control Center — for when they click on the link or button.

Here’s an example of how you might do that:

public class MainLayout extends AppLayout {

    public MainLayout() {
         1
        Button loginButton = new Button("Login", event -> {
            getUI().ifPresent(ui -> ui.getPage().setLocation("/oauth2/authorization/control-center"));
        });

         2
        Anchor loginLink = new Anchor("/oauth2/authorization/control-center", "Login");
        loginLink.setRouterIgnore(true);

        addToNavbar(loginButton, loginLink);
    }
}
  1. This part creates a login button.

  2. This creates a login link.

You probably wouldn’t want both a button and a link. You’ll have to decide which you want, and disregard the other in this example.

Adding Logout

To add a logout link or button to a Vaadin application, you’ll need to create a component that triggers the logout process.

Here’s an example of how to create only a button:

public class MainLayout extends AppLayout {

    public MainLayout(@Autowired AuthenticationContext authenticationContext) {

        Button logoutButton = new Button("Logout", click -> authenticationContext.logout());

        addToNavbar(logoutButton);
    }
}

Combining

You can combine the login and logout buttons in the same layout. When doing this, you should display the relevant one based on the user’s authentication status. Here’s an example of how you might do that:

public class MainLayout extends AppLayout {

    public MainLayout(@Autowired AuthenticatedUser authenticationContext) {

        if (authenticationContext.isAuthenticated()) {
            Button logoutButton = new Button("Logout", click -> authenticationContext.logout());
            addToNavbar(logoutButton);
        } else {
            Button loginButton = new Button("Login", event -> {
                getUI().ifPresent(ui -> ui.getPage().setLocation("/oauth2/authorization/control-center"));
            });
            addToNavbar(loginButton);
        }
    }
}

Deploy the Application

To deploy the application, see Deploying a Vaadin Application with Control Center. Be sure to activate the Identity Management feature.