如果当前用户是特定类型,我的应用程序仅允许访问,这也意味着他们拥有的角色可以登录到其他应用程序,然后访问具有特定角色的应用程序的某些部分,例如,我的Web应用程序配置为
<security-role>
<role-name>teamb</role-name>
</security-role>
现在我需要的是能够在我的应用中访问有关此角色的详细信息,即用户名
如何在我的Spring MVC
应用中执行此操作?
答案 0 :(得分:14)
首先,在页面中包含相应的标记库(我将使用JSP创建一个示例)
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
然后你只需要使用这些标签来查询权限,当然还有数据。
查看用户是否拥有足够的权限:
<sec:authorize ifAllGranted="ROLE_ADMIN">
<a href="page.htm">Some Admin Stuff</a>
</sec:authorize>
如果用户拥有足够的权限,则会呈现指向page.htm
的链接。
要获取用户名,请使用${SPRING_SECURITY_LAST_USERNAME}
。这是一个注销链接作为例子:
<a href="<c:url value="/j_spring_security_logout" />">Logout <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></a>
修改强>
要查询当前经过身份验证的用户,您可以尝试不同的方法:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
或
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User)authentication.getPrincipal();
user.getUsername();
在调用authentication
或getName
方法之前,请记住检查getPrincipal
是否为空。