Java Spring MVC获取当前登录用户
仅当当前用户为特定类型时,我的应用才允许访问,这也意味着他们所拥有的角色可以登录到其他应用程序,然后使用特定角色访问我的应用程序的某些部分,例如,我的web应用程序配置为Java Spring MVC获取当前登录用户,java,spring-mvc,spring-security,Java,Spring Mvc,Spring Security,仅当当前用户为特定类型时,我的应用才允许访问,这也意味着他们所拥有的角色可以登录到其他应用程序,然后使用特定角色访问我的应用程序的某些部分,例如,我的web应用程序配置为 <security-role> <role-name>teamb</role-name> </security-role> 团队B 现在我需要的是能够在我的应用程序中访问有关此角色的详细信息,即用户名 如何在我的springmvc应用程序中做到这一点?
<security-role>
<role-name>teamb</role-name>
</security-role>
团队B
现在我需要的是能够在我的应用程序中访问有关此角色的详细信息,即用户名
如何在我的
springmvc
应用程序中做到这一点?首先,在页面中包含相应的标记库(我将使用JSP制作一个示例)
编辑
要查询当前经过身份验证的用户,您可以尝试不同的方法:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
或
在调用
getName
或getPrincipal
方法之前,请记住检查authentication
是否不为null。Hi Gamb,谢谢。。但那不是我想要的。我基本上设置了web.xml,以便特定的url只允许具有特定角色的用户访问。例如。。。myapp/showdetails/受admin类型角色的保护。我有其他应用程序可以访问此url,如果它们设置了角色。。因此,另一个应用程序设置了此角色,并且他们访问此url。。在我的控制器中,我试图获取用户名。。这就是我被卡住的地方,因为我只得到了“匿名用户”@user1555190哦,我明白了。我将编辑我的答案并建议另一种方法。目前,您还可以使用方法“getUserPrincipal()”从WebRequest(特定于Spring的请求类型)获取用户详细信息
<sec:authorize ifAllGranted="ROLE_ADMIN">
<a href="page.htm">Some Admin Stuff</a>
</sec:authorize>
<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();