Role-Based Access Control for Views
- Define Roles with Spring Security
- Using Roles in TypeScript
- Routes with Access Control
- Hiding Unauthorized Menu Items
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. See Authentication With Spring Security to set that up; that page also defines the auth.ts helpers and the UserInfo bean that the examples here build on.
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 browser-callable service that gets user information, including roles, from Java during authentication. The UserInfo bean defined in Authentication With Spring Security already carries the authorities of the logged-in user, so all that’s needed is a service method that returns it to the client:
Source code
UserInfoService.java
The auth.ts helpers from the same page store that user information on login, and provide the isUserInRole() helper that the access checks below build on:
Source code
auth.ts
auth.tsRoutes 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
routes.tsAdd a method to check access for the given route by iterating rolesAllowed, using isUserInRole(), as follows:
Source code
routes.ts
routes.tsThen use the method added in the route action to redirect on unauthorized access like this:
Source code
routes.ts
routes.ts