I'm using Spring security to authenticate user in my web page. I would like to show for each user his roles without bracket. If I use
<p sec:authentication='principal.authorities'></p>
I see [ADMIN, USER]. Is there a way in thymeleaf, javascript or HTML to show only ADMIN,USER? I know that in thymeleaf there is spring replace but how can I pass the result of above code? Thanks, regards
I'm using Spring security to authenticate user in my web page. I would like to show for each user his roles without bracket. If I use
<p sec:authentication='principal.authorities'></p>
I see [ADMIN, USER]. Is there a way in thymeleaf, javascript or HTML to show only ADMIN,USER? I know that in thymeleaf there is spring replace but how can I pass the result of above code? Thanks, regards
Share Improve this question asked Dec 17, 2015 at 14:16 lucaluca 3,32811 gold badges69 silver badges149 bronze badges3 Answers
Reset to default 5thymeleaf-extras-springsecurity provides access to an #authentication
object which can return the list of GrantedAuthorities. There will be a GrantedAuthority for each role assigned (prefixed by 'ROLE_').
You can use this to loop through and display each role (removing the ROLE_ prefix):
<p th:each="authority : ${#authentication.getAuthorities()}"
th:if="${authority.getAuthority().startsWith('ROLE_')}"
th:text="${authority.getAuthority().replaceFirst('ROLE_', '')}">
</p>
Sorry, late to this thread, but here is a working solution using Thymeleaf and Thymeleaf Extras
Role(s):
<th:block th:each="r, iter:${#authentication.getAuthorities()}">
<span th:text="${r}"></span>
<th:block th:if="${!iter.last}">, </th:block>
</th:block>
The code above will add a ma except after the last role.
I think you see the brackets because 'principal.authorities' is an array. Try with the jstl taglib.
<%@ taglib uri="http://java.sun./jsp/jstl/core" prefix="c" %>
...
<c:forEach var="item" items="principal.authorities">
<c:out value="${item}"/>
</c:forEach>
...