我有一个使用Spring Security的Spring MVC Web应用程序.我想知道当前登录用户的用户名.我正在使用下面给出的代码段.这是接受的方式吗?
我不喜欢在这个控制器中调用静态方法 - 这违背了Spring的全部目的,恕我直言.有没有办法配置应用程序以注入当前的SecurityContext或当前的身份验证?
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
Run Code Online (Sandbox Code Playgroud) 在我的控制器中,当我需要活动(登录)用户时,我正在执行以下操作来获取我的UserDetails实现:
User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.debug(activeUser.getSomeCustomField());
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我认为Spring可以在这样的情况下让生活更轻松.有没有办法将UserDetails自动装配到控制器或方法?
例如,类似于:
public ModelAndView someRequestHandler(Principal principal) { ... }
Run Code Online (Sandbox Code Playgroud)
但是,而不是得到UsernamePasswordAuthenticationToken,我得到了一个UserDetails?
我正在寻找一个优雅的解决方案.有任何想法吗?
可能重复:
使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?
spring security如何检索用户名
我使用spring ldap来验证我的网络应用程序,
<ldap-server id="sss" port="389"
url="ldap://ldap.example.com:389/ou=active,ou=employees,ou=people,o=example.com?uid?sub"/>
<authentication-manager alias="authenticationManager">
<ldap-authentication-provider
server-ref="sss"
role-prefix="ROLE_">
</ldap-authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)
它工作,但我不知道如何在登录页面填写用户名,因为我想在我的页面顶部显示它.
谢谢.