在不带括号的HTML页面中显示用户角色

Show user roles in HTML page without bracket

本文关键字:显示 用户 角色 HTML      更新时间:2023-09-26

我正在使用Spring安全性对网页中的用户进行身份验证。我想为每个用户显示他的角色,没有括号。如果我使用

<p sec:authentication='principal.authorities'></p>

我看到[ADMIN,USER]。在thymelaf、javascript或HTML中有没有一种方法可以只显示ADMIN、USER?我知道在thymelaf中有spring-replace,但我如何才能传递上面代码的结果?谢谢,问候

thymelaf extra springsecurity提供对#authentication对象的访问,该对象可以返回GrantedAuthority列表。分配的每个角色都将有一个GrantedAuthority(前缀为"role_")。

您可以使用它来循环并显示每个角色(删除role_前缀):

    <p th:each="authority : ${#authentication.getAuthorities()}"
       th:if="${authority.getAuthority().startsWith('ROLE_')}"
       th:text="${authority.getAuthority().replaceFirst('ROLE_', '')}">
    </p>

很抱歉,这个线程来晚了,但这里有一个使用Thymelaf和Thymelaf-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>

上面的代码将在最后一个角色之后添加一个逗号。

我认为您看到了括号,因为"principal.authority"是一个数组。尝试使用jstl标签库。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach var="item" items="principal.authorities">
   <c:out value="${item}"/>
</c:forEach>
...