1、如果在jsp页面中获取可以使用spring security的标签
页面引入标签
- <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
使用:
- <div> username : <sec:authentication property="name"/></div>
即可显示当前用户。
2.java代码中使用
- 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中,此对象中有当前用户的各种资料
- 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());
- }