Enabling Submit on User Role in Thymeleaf and Spring

I’m going to be putting a demo version of my NixMash Spring GitHub app online soon and want to tighten down some of its functionality to reduce maintenance on my part. One thing would be to restrict certain Update and Create Submit Buttons to Administrators Only.

The “Update” button below is restricted to users in the Admin Role, for instance.

Here’s how I’m doing it in Thymeleaf.

<input type="submit" ... th:disabled="!${currentUser.user.hasAuthority('ROLE_ADMIN')}" />

CurrentUser is an object based on @AuthenticationPrincipal that we’re providing to all pages through a @ControllerAdvice method.

Another thing to remember is Thymeleaf’s Spring Security Dialect and Expression Utility Objects. For more on that see the Thymeleaf Extras Spring Security Readme on GitHub. One of those Security Expressions is


That gives us access to all of Spring Security’s Access Control Expressions like hasRole([role]) and isAnonymous(). With that in our toolkit we can enable the Submit button with:

<input type="submit" ... th:disabled="!${#authorization.expression('hasRole(''ROLE_ADMIN'')')}" />I think using CurrentUser is cleaner (and it spares you the goofy multiple quotes around ROLE_ADMIN), but it’s a great access tool to have available.