Viking
Viking

Reputation: 177

Thymeleaf Swich with Spring Security

I'm trying to build an eshop. I want to create a page that, when viewed by a User, only shows those items which quantity is greater than 0, but when Administrator viewing the same page, they can see all items and can add/edit/delete items regardless of whether the quantity is 0 or more. I think maybe I can use Thymeleaf with Spring Security like this:

 <div th:switch=sec:authorize="hasAuthority('admin')">
        <div th:case="'admin'" class="tilt pic" id="whoKnows" >
        <div th:case="'user'" class="tilt pic"  th:unless="${viewAvailableWhisky.quantityWhisky} == 0">

but it's not working.

It's a joke? two people edit my text, but they don't know answer...

Upvotes: 0

Views: 515

Answers (2)

Scaramouche
Scaramouche

Reputation: 3267

Two years later.

If you would want to stick to the th:switch approach, this could be a way:

<div th:switch="${#authorization.expression('hasAuthority(''ROLE_ADMIN'')')}">
    <div th:case="true" class="tilt pic" id="whoKnows">ADMIN</div>
    <div th:case="false" class="tilt pic" 
         th:unless="${viewAvailableWhisky.quantityWhisky} == 0">USER</div>
</div>

Upvotes: 1

DarkAtra
DarkAtra

Reputation: 1232

From http://www.thymeleaf.org/doc/articles/springsecurity.html:

The sec:authorize attribute renders its content when the attribute expression is evaluated to true

Just use sec:authorize directly:

<div sec:authorize="hasAuthority('admin')" class="tilt pic" id="whoKnows"></div>
<div sec:authorize="hasAuthority('user')" class="tilt pic"  th:unless="${viewAvailableWhisky.quantityWhisky} == 0"></div>

Your solution doesn't work because your switch condition will resolve to true or false but not to 'admin' or 'user'. hasAuthority('admin') will resolve to true if the user has the 'admin' authority and to false if not.

Upvotes: 0

Related Questions