在JSP EL表达式中获取Spring Security Principal


问题内容

我正在使用Spring MVC和Spring
Security版本3.0.6.RELEASE。在我的JSP中获得用户名的最简单方法是什么?甚至只是用户是否已登录?我可以想到几种方法:

1.使用脚本

使用如下脚本来确定用户是否已登录:

<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
    .getAuthentication().getPrincipal().equals("anonymousUser")
    ? "false":"true"%>

不过,我不喜欢使用scriptlet,我想在某些<c:if>标签中使用它,这需要将其作为page属性放回去。

2.使用SecurityContextHolder

我可以再次使用我的SecurityContextHolder
@Controller并将其放在模型上。不过,我在每个页面上都需要此逻辑,因此我宁愿不必在每个Controller中都添加此逻辑。

我怀疑有更干净的方法可以做到这一点…


问题答案:

检查Spring安全标签: <sec:authentication property="principal.username" />

http://static.springsource.org/spring-
security/site/docs/3.0.x/reference/taglibs.html

您可以检查是否已记录:

<sec:authorize access="isAuthenticated()">

而不是c:if