Thymeleaf sec:authorize vs @PreAuthorize: Which Layer Prevents Accidental Public Access?
0 reputation · 28 Apr 2026, 05:35 UTC
Authorization at the template layer versus the controller layer
Thymeleaf's sec:authorize attribute hides UI fragments based on Spring Security expressions, while @PreAuthorize on controller methods blocks unauthorized requests before any template executes. Both use SpEL syntax such as hasRole('ADMIN'), yet they operate at different stages of the request lifecycle.
Constraint: defense in depth without duplication
Applying @PreAuthorize to every protected endpoint guarantees that direct API calls, bookmarked URLs, or curl requests receive a 403. Adding sec:authorize to the corresponding templates keeps navigation links and page sections consistent with the same policy. The trade-off is maintaining two declaration sites for the same authority rule.
Uncertainty: expression parity and fragment exposure
- Spring Security automatically prefixes
ROLE_in@PreAuthorizebut not insec:authorize, so the literal strings must match the stored authorities. - Fragments included via
th:replaceinherit the surroundingsec:authorizecontext, yet a fragment-only endpoint exposed as a separate@GetMappingwould need its own@PreAuthorize.
Which combination of template-level and method-level annotations provides complete coverage for a Spring Boot 3.x application using Thymeleaf 3.1 and Spring Security 6.x, and how should the authority expressions be written to stay in sync?