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中,此对象中有当前用户的各种资料 但我在实际运用中发现获得的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());// 获得sessionidSystem.out.println("SessionId" + details.getSessionId());// 获得当前用户所拥有的权限Listauthorities = (List ) securityContextImpl.getAuthentication().getAuthorities();for (GrantedAuthority grantedAuthority : authorities) {System.out.println("Authority" + grantedAuthority.getAuthority());}