Spring MVC获取当前登录用户

use*_*190 8 java spring-mvc spring-security

如果当前用户是特定类型,我的应用程序仅允许访问,这也意味着他们拥有的角色可以登录到其他应用程序,然后访问具有特定角色的应用程序的某些部分,例如,我的Web应用程序配置为

<security-role> 
   <role-name>teamb</role-name>       
</security-role>
Run Code Online (Sandbox Code Playgroud)

现在我需要的是能够在我的应用程序中访问有关此角色的详细信息,即用户名

我怎么能在我的Spring MVC应用程序中执行此操作?

Fri*_*itz 15

首先,在页面中包含相应的标记库(我将使用JSP进行示例)

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
Run Code Online (Sandbox Code Playgroud)

然后你只需要使用这些标签来查询权限,当然还有数据.

要查看用户是否具有足够的权限:

<sec:authorize ifAllGranted="ROLE_ADMIN">
    <a href="page.htm">Some Admin Stuff</a>
</sec:authorize>
Run Code Online (Sandbox Code Playgroud)

如果用户具有足够的权限,page.htm则将呈现链接.

要获取用户名${SPRING_SECURITY_LAST_USERNAME}.这是一个注销链接作为示例:

<a href="<c:url value="/j_spring_security_logout" />">Logout <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></a>
Run Code Online (Sandbox Code Playgroud)

编辑

要查询当前经过身份验证的用户,您可以尝试不同的方法:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
Run Code Online (Sandbox Code Playgroud)

要么

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User)authentication.getPrincipal();
user.getUsername();
Run Code Online (Sandbox Code Playgroud)

只需记住authentication在调用getNamegetPrincipal方法之前检查是否为null .