如果当前用户是特定类型,我的应用程序只允许访问,这也意味着他们拥有的角色可以登录其他应用程序,然后以特定角色访问我的应用程序的某些部分,例如,我的网络应用程序配置为
<security-role>
<role-name>teamb</role-name>
</security-role>
现在我需要的是能够在我的应用程序中访问有关此角色的详细信息,即用户名
如何在我的 Spring MVC
应用程序中执行此操作?
最佳答案
首先,在你的页面中包含相应的标签库(我用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();
请记住在调用 getName
或 getPrincipal
方法之前检查 authentication
是否不为 null。
关于java - Spring MVC 获取当前登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428033/