如何使用 spring 安全性访问 JSP 中的角色?

2022-09-02 02:49:35

我想在 JSP 中打印用户角色?我知道有一个名为“使用此标签”的弹簧-安全标签,我可以访问用户名。但是如何在jsp中访问和打印当前角色?<sec:authentication property="principal.username"/>


答案 1

由于 引用了您的对象,因此,如果检查该对象,则角色将存储在 下。principalUserDetailspublic Collection<GrantedAuthority> getAuthorities() { .. }

也就是说,如果您只想在屏幕上打印角色,请执行以下操作:

<sec:authentication property="principal.authorities"/>

答案 2

使用 getAuthorities 或编写您自己的用户详细信息实现,并创建一个方便的方法。

或:

<sec:authorize access="hasRole('supervisor')">
 This content will only be visible to users who have
 the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
</sec:authorize>

从这里 .