Docs

Getting Started

Step-by-step guide on how to use SSO Kit in a Hilla application.
Note
Instructions for Hilla
This page guides you in getting started with SSO Kit and Hilla. See the guide for getting stated with SSO Kit and Vaadin Flow.

SSO Kit builds upon Spring Boot and Spring Security. It comes with a starter and client side modules for configuring the security settings needed to authenticate with an identity provider.

Create a Project

Create a Vaadin project as described in Getting Started, and add the Hilla Spring Boot starter to it as described in Enabling Browser-Callable Services in a Vaadin Project. Without that dependency, no TypeScript clients are generated for browser-callable services, and the React views under src/main/frontend/views are ignored.

Note
Examples Refer to Starter Files
The steps below refer to files from a starter project as examples: a browser-callable service named HelloWorldEndpoint, an About view, and a MainLayout. Apply them to the services and views your own project has.

Backend

Once you have a project, you can begin securing it by installing and configuring SSO Kit on the backend. The following section shows how to block unauthorized users from using a button in an application. You can install and update SSO Kit by adding it as a dependency to your application in the pom.xml file.

Add SSO Kit Dependency

Add the sso-kit-starter-hilla module — the flavor of the starter that comes with the services and the client-side context that React views use — to the pom.xml file of a Vaadin application like so:

Source code
pom.xml
<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>sso-kit-starter-hilla</artifactId>
</dependency>

The version comes from the vaadin-bom dependency management that the project already has.

TypeScript Client Generation

SSO Kit registers its own browser-callable services as Spring beans, so TypeScript clients are generated for them together with your application’s services. No generator configuration is needed.

Configure SSO Provider in Spring

Next, you need to set some configuration properties to connect SSO Kit to an OpenID Connect provider. These properties can be added to your application.properties file where you give the provider URL and the client registration details, such as credentials and scope.

Provider definition is configured within the spring.security.oauth2.provider namespace where you give a key to identify your provider, such as keycloak. You can use the same key to register the client for that provider within the spring.security.oauth2.registration namespace, where you specify client credentials and the requested scope.

The scope is a list of keywords to request the provider for a specific set of information, such as user profile, email, and roles. The following is an example of the properties to set to enable a Keycloak instance to perform authentication:

Source code
application.properties
spring.security.oauth2.client.registration.keycloak.scope=profile,openid,email,roles
# Customize the following property values for your Keycloak configuration:
spring.security.oauth2.client.provider.keycloak.issuer-uri=https://my-keycloak.io/realms/my-realm
spring.security.oauth2.client.registration.keycloak.client-id=my-client
spring.security.oauth2.client.registration.keycloak.client-secret=very-secret-value
application.yaml

Single Sign-On

SSO Kit provides the SingleSignOnConfiguration auto-configuration class to set up Hilla and Spring to allow single sign-on with external identity providers.

Note
Customized Security Configuration
If you need a customized security configuration, you can disable this auto-configuration class by adding its fully-qualified name to the spring.autoconfigure.exclude property and define your own configuration class.

The following configuration enables login for the identity providers defined in the application configuration. It instructs the application to accept requests for the login route. It can be configured by setting the hilla.sso.login-route property, which defaults to /login.

To redirect users automatically to the provider login form, you can set this property to /oauth2/authorization/{provider-key}, where {provider-key} is the key used to configure the provider in application.properties file.

Source code
application.properties
hilla.sso.login-route=/oauth2/authorization/keycloak
application.yaml
Tip
Custom Login Page
Some providers support a custom theme for their login pages. Learn more about this in Theming.

Secure the Application

A Hilla application includes frontend code and backend services. Both of them can and should benefit from authentication protection.

Protect the Example Service

Hilla allows fine-grained authorization on browser-callable services and their methods. You can use annotations like @PermitAll or @RolesAllowed(…​) to declare who can access what.

To try this feature, replace the @AnonymousAllowed annotation in HelloWorldEndpoint.java with @PermitAll. When you do this, unauthenticated users won’t be able to access all service methods. You could also apply the same annotation at the method level for more fine-grained control.

Start the application using the mvnw command. Then try the application in the browser. It should work correctly, except that when you click on the Say Hello button, nothing happens. This is because the service is no longer accessible without authentication.

Frontend

Once the backend is secure, you can begin extending authentication features to the frontend. The following section shows how to display user information (e.g., a name), on secured views and enable users to log in and out.

Install SSO Kit Client Dependency

Source code
bash
npm install --save @vaadin/sso-kit-client-react

This dependency contains the SsoProvider provider and the useSsoContext hook which are needed in the later steps.

Add SSO Provider

The SsoProvider provides the single sign-on context to the application. Import the SsoProvider and pass the RouterProvider as a parameter to it in the App.tsx file.

Source code
frontend/App.tsx
import { SsoProvider } from '@vaadin/sso-kit-client-react';

return (
  <SsoProvider>
    <RouterProvider router={router}/>
  </SsoProvider>
);

Add Log-In & Log-Out Buttons

As an example, add two buttons to the drawer footer — one to sign in, and another to sign out. Use the imported useSsoContext hook to get the authenticated state and to add the login and logout functions to the buttons.

Source code
frontend/views/MainLayout.tsx
import { Button } from '@vaadin/react-components/Button.js';
import { useSsoContext } from '@vaadin/sso-kit-client-react';

// Get the authenticated state, the login and logout functions in the MenuOnLeftLayout function.
const {authenticated, login, logout} = useSsoContext();

// Replace the `footer` in the returned element.
<footer slot="drawer">
  {authenticated
    ? <Button onClick={logout}>Sign out</Button>
    : <Button onClick={login}>Sign in</Button>
  }
</footer>

Add Access Control

You can protect your views by verifying that each authentication has happened before loading the view.

Tip
Custom Redirect Path
You can define a custom redirect path in the protectRoutes function on which to redirect users that are not authenticated. The default value is the predefined /ssologin path, which redirects the user to the provider’s login page.

In the frontend/routes.tsx file, enrich the ViewRouteObject type with AccessProps type to be able to protect a view and add the requireAuthentication parameter to a view:

Source code
frontend/routes.tsx
import { AccessProps, protectRoutes } from '@vaadin/sso-kit-client-react';

// Enrich the ViewRouteObject type with AccessProps.
export type ViewRouteObject = (IndexViewRouteObject | NonIndexViewRouteObject) & AccessProps;

// Add requireAuthentication to the About View.
{
  path: '/about',
  // ...
  requireAuthentication: true,
},

// Protect the views which require authentication.
export const routes: readonly ViewRouteObject[] = protectRoutes([
  // ...
]);

Filter the menu excluding unauthorized views by amending the view filter in MainLayout.tsx:

Source code
frontend/views/MainLayout.tsx
// Gather the hasAccess function and add filter to the routes that checks for authentication.
const { hasAccess } = useSsoContext();

const menuRoutes = (routes[0]?.children || [])
  .filter((route) => route.path && route.handle && route.handle.icon && route.handle.title)
  .filter(hasAccess) as readonly MenuRoute[];

Now the About item in the menu appears only when authenticated.

Show User Information

The SSO Kit Client provides the User class which contains information about the authenticated user. You can get the user information by using the useSsoContext hook.

Since the About page is now protected, it’s a perfect place to show some information about the current user:

Source code
frontend/views/about/AboutView.tsx
import { useSsoContext } from '@vaadin/sso-kit-client-react';

// Gather the user from the SSO context.
const { user } = useSsoContext();

// Add some output in the return.
<p>Username: {user?.preferredUsername}</p>
<p>Full name: {user?.fullName}</p>
<p>Email: {user?.email}</p>

Single Sign-Off

SSO Kit provides two methods for logging out the user. They’re defined by the OpenID Connect specification like so:

RP-Initiated Logout

RP-initiated logout (i.e., Relaying Party, the application) enables the user to logout from the application itself, ensuring the connected provider session is terminated.

Back-Channel Logout

Back-Channel Logout is a feature that enables the provider to close user sessions from outside the application. For example, from the provider’s user dashboard or from another application.

Enable the Feature

Since SSO Kit 3.1, this feature is enabled by default through Spring Security’s Back-Channel Logout filters. Configure the client on the provider’s dashboard to send logout requests to: /logout/connect/back-channel/{registration-key}, where {registration-key} is the provider key.

Warning
Built-In Implementation Deprecated
The kit’s built-in Back-Channel Logout implementation, activated with hilla.sso.back-channel-logout=true, is deprecated since SSO Kit 3.1. It’s retained only for backwards compatibility with applications that depend on the legacy behavior. Don’t enable it on new projects: Spring Security’s filters are already active by default and cover the same feature.

Modify the Frontend

As an example, show a dialog when the user is logged out from outside the application.

The useSsoContext hook provided by the SSO Kit Client handles the back-channel logout and receives an event if logout happens. To get notified about a logout event, register a callback using the onBackChannelLogout function and store the logged out state:

Source code
frontend/views/MainLayout.tsx
import { ConfirmDialog } from '@vaadin/react-components/ConfirmDialog.js';
import { useEffect } from 'react';
import { useSignal } from '@vaadin/hilla-react-signals';
import { useSsoContext } from '@vaadin/sso-kit-client-react';

const { onBackChannelLogout } = useSsoContext();

// Store the logged out state.
const loggedOut = useSignal(false);
// Subscribe to the back-channel logout event and set logged out state to true on the event.
useEffect(() => {
  onBackChannelLogout(() => {
    loggedOut.value = true;
  });
}, []);

// Add the confirm dialog to the AppLayout.
<ConfirmDialog header='Logged out' cancelButtonVisible
             opened={loggedOut.value}
             onConfirm={login}
             onCancel={logout}
>
<p>You have been logged out. Do you want to log in again?</p>
</ConfirmDialog>

You can trigger a logout externally with the provider tools. For Keycloak, you can sign out a session from the administration console or visit the page https://my-keycloak.io/realms/my-realm/protocol/openid-connect/logout.

4eb1584e-cb6e-4cc8-be46-d6520feb0b41

Updated