java Spring MVC 获取当前登录用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12428033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:51:06  来源:igfitidea点击:

Spring MVC get current logged in user

javaspring-mvcspring-security

提问by user1555190

My app only allows access if the current user is a specific type, this also means the role they have can log into other applications and then access certain parts of my app with specific roles, for example, my web app is configured that

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

<security-role> 
   <role-name>teamb</role-name>       
</security-role>

Now what I need is to be able access the details regarding this role in my app, ie.e user name

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

how can I do this in my Spring MVCapp?

我怎样才能在我的Spring MVC应用程序中做到这一点?

回答by Fritz

First of all, include the corresponding tag library in your pages (I'll make an example using JSP)

首先,在你的页面中包含相应的标签库(我会用JSP做一个例子)

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Then you just have to use those tags to query for permissions and of course, the data.

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

To see if an user has enough privileges for something:

要查看用户是否具有足够的权限,请执行以下操作:

<sec:authorize ifAllGranted="ROLE_ADMIN">
    <a href="page.htm">Some Admin Stuff</a>
</sec:authorize>

If the user has enough privileges, the link to page.htmwill be rendered.

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

To get the username use ${SPRING_SECURITY_LAST_USERNAME}. Here's a logout link as an example:

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

<a href="<c:url value="/j_spring_security_logout" />">Logout <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></a>

Edit

编辑

To query the currently authenticated user you can try different approaches:

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

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();

or

或者

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User)authentication.getPrincipal();
user.getUsername();

Just remember to check if authenticationis not null before invoking the getNameor getPrincipalmethods.

请记住authentication在调用getNameorgetPrincipal方法之前检查是否为空。