Docs

Documentation versions (currently viewingVaadin 24)
Documentation translations (currently viewingEnglish)

Role-Based Access Control for Views

How to restrict access for selected Hilla views based on roles defined for the logged-in user.

It’s possible to restrict access for selected Hilla views, based on roles defined for the logged-in user. This article explains how to do this.

To follow the examples here, you’ll need a Hilla application with authentication enabled. The Authentication With Spring Security page will help you to get started.

Define Roles with Spring Security

Roles are a set of string attributes representing the authorities that are assigned to a user. In Spring Security, the user details used for authentication also specify roles.

Typically, roles are defined in authority strings prefixed with ROLE_. After successful authentication, these are accessible via the GrantedAuthority objects returned by Authentication.getAuthorities(). See the Authentication With Spring Security page for examples of configuration.

Using Roles in TypeScript

A convenient way to use roles for access control in TypeScript views is to add a Hilla endpoint that gets user information, including roles, from Java during authentication. To do this, first define a bean representing information about the user:

Source code
UserInfo.java

Next, add the endpoint to get a UserInfo containing authorities for the logged-in user on the client side:

Source code
UserInfoService.java

Then, change the authentication implementation in TypeScript to get the user information from the endpoint. Change the auth.ts defined in Authentication With Spring Security as follows:

Source code
auth.ts

Add an isUserInRole() helper, which enables role-based access control checks for the UI.

Source code
auth.ts

Routes with Access Control

To enable allowed roles to be specified on the view routes, define an extended type ViewRoute, that has a rolesAllowed string, like so:

Source code
routes.ts

Add a method to check access for the given route by iterating rolesAllowed, using isUserInRole(), as follows:

Source code
routes.ts

Then use the method added in the route action to redirect on unauthorized access like this:

Source code
routes.ts

Hiding Unauthorized Menu Items

Filter the route list using the isAuthorizedViewRoute() helper defined earlier. Then use the filtered list of routes as menu items:

Source code
main-view.ts