1:如果在jsp页面中获取可以使用spring security的标签库
在页面中引入标签
1 | <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> |
然后:
1 | <div> username : <sec:authentication property="name"/></div> |
即可显示当前用户。
2:如果要在程序中获得
看了网上很多写法都是在程序中写这样的代码
1 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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()); } |