1、如果在jsp页面中获取可以使用spring security的标签

页面引入标签

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

使用:

  1. <div> username : <sec:authentication property="name"/></div>
<div> username : <sec:authentication property="name"/></div>

即可显示当前用户。

2.java代码中使用

  1. UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
 UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();

但我在实际运用中发现获得的Authentication为null。仔细看了下源代码发现,如果想用上面的代码获得当前用户,必须在spring

security过滤器执行中执行,否则在过滤链执行完时org.springframework.security.web.context.SecurityContextPersistenceFilter类会

调用SecurityContextHolder.clearContext();而把SecurityContextHolder清空,所以会得到null。    经过spring security认证后,

security会把一个SecurityContextImpl对象存储到session中,此对象中有当前用户的各种资料

  1. SecurityContextImpl securityContextImpl = (SecurityContextImpl) request
  2. .getSession().getAttribute("SPRING_SECURITY_CONTEXT");
  3. // 登录名
  4. System.out.println("Username:"
  5. + securityContextImpl.getAuthentication().getName());
  6. // 登录密码,未加密的
  7. System.out.println("Credentials:"
  8. + securityContextImpl.getAuthentication().getCredentials());
  9. WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl
  10. .getAuthentication().getDetails();
  11. // 获得访问地址
  12. System.out.println("RemoteAddress" + details.getRemoteAddress());
  13. // 获得sessionid
  14. System.out.println("SessionId" + details.getSessionId());
  15. // 获得当前用户所拥有的权限
  16. List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl
  17. .getAuthentication().getAuthorities();
  18. for (GrantedAuthority grantedAuthority : authorities) {
  19. System.out.println("Authority" + grantedAuthority.getAuthority());
  20. }
SecurityContextImpl securityContextImpl = (SecurityContextImpl) request
.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
// 登录名
System.out.println("Username:"
+ securityContextImpl.getAuthentication().getName());
// 登录密码,未加密的
System.out.println("Credentials:"
+ securityContextImpl.getAuthentication().getCredentials());
WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl
.getAuthentication().getDetails();
// 获得访问地址
System.out.println("RemoteAddress" + details.getRemoteAddress());
// 获得sessionid
System.out.println("SessionId" + details.getSessionId());
// 获得当前用户所拥有的权限
List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl
.getAuthentication().getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
System.out.println("Authority" + grantedAuthority.getAuthority());
}

05-11 02:36