Reputation: 183
I'm using Thymeleaf with spring security. In html code I'm checking user role:
<li class="has-sub" sec:authorize="hasRole('ROLE_ADMIN')">
</li>
but in spring I implemented own CustomSecurityExpressionRoot
so I can use in controller for example
@PreAuthorize("hasAccess('PERMISSION')")
It is possible to connect Thymeleaf to be able to use hasAccess
(and others) methods from my CustomSecurityExpressionRoot
?
Upvotes: 2
Views: 689
Reputation: 4132
I used something similar to the posted answer with getting the authentication that way:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class AccessEvaluator {
public boolean hasAccess(String pageName) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return ((MyUserPrincipal) auth.getPrincipal()).getAccessOnPage(pageName);
}
}
And call it as below:
<li th:if="${@accessEvaluator.hasAccess('ACT')}" >
<p> I have access on ACT page </p>
</li>
Upvotes: 1
Reputation: 16644
I would have put the logic in a singleton Spring bean:
@Component
public class AccessEvaluator {
public boolean hasAccess(Authentication authentication, String permission) {
// implementation
}
}
And then in Thymeleaf code:
<li th:if="${@accessEvaluator.hasAccess(#request.userPrincipal, 'PERMISSION')}">
</li>
Upvotes: 2