Spring Security - 显示特定于登录用户的内容

Posted

技术标签:

【中文标题】Spring Security - 显示特定于登录用户的内容【英文标题】:Spring Security - showing content specific to the logged in user 【发布时间】:2013-01-05 18:54:41 【问题描述】:

假设我有一个个人资料页面,其中有一个“编辑您的个人资料”链接。所有用户都可以查看个人资料页面,但编辑链接按钮应该只对查看其个人资料的登录用户可见,而不是其他用户的个人资料。

到目前为止,我有这个代码,

<sec:authorize access="isAuthenticated()">
<sec:authentication property="principal.username" var="principal"/>
<c:if test="$profile_username eq principal">   <!--profile_username is the username of the viewed profile  -->
<!-- edit your profile link -->
</c:if>
</sec:authorize>    

有没有更清洁的方法来做到这一点?可能是一个像

&lt;sec:authorize access="isTheSamePerson()"/&gt;.

提前致谢。 :)

【问题讨论】:

您不应该需要 sec:authorize 标签,如果用户没有登录,则主体对象将为空,并且 c:if 测试将失败。不完全是你想要的,但它会清理一点。 不错的收获。但是,如果没有 sec:auth 标签,这是行不通的。它会抛出异常。 【参考方案1】:

您要考虑实际的域对象。为了这些目的,Spring Security 中有一个特殊的 ACL 功能。您可以设置它并使用相应的accesscontrollist标签:

<sec:accesscontrollist hasPermission="2" domainObject="$profile">
    <!-- Your edit link goes here -->
    <!-- "2" means write permission -->
    <!-- Be sure that you use Spring Security >= 3.1.2. This syntax may not works for smaller versions due to bugs  -->
</sec:accesscontrollist>

如果你只有这样一种情况,这可能是矫枉过正。

选项编号 2。您可以定义自定义网络安全表达式:

<sec:authorize access="isOwner(#profile)"/>.

不是so simple too。

我认为自定义 JSP 标签 (tag file) 将是最简单的解决方案:

<customtags:authorizeeditaccount account="$profile"/> 

这个标签会做同样的事情。看起来会好很多。

【讨论】:

很好的解决方案如果我的案例太多。否则就大材小用了。

以上是关于Spring Security - 显示特定于登录用户的内容的主要内容,如果未能解决你的问题,请参考以下文章

对特定于 Spring 引导测试的 @TestConfiguration 感到困惑

如何在 Spring Cloud Gateway 中添加特定于路由的自定义过滤器

在 Spring Cloud GCP pubsub 中创建特定于消息通道的线程

由于重定向循环,Grails Spring Security 无法显示登录页面

CSRF 攻击是不是特定于目标网站

显示登录用户spring security