1.1. 获取已登录用户信息
在使用Spring Security的应用程序中,可以通过SecurityContext接口获取到已经登录的用户的信息。SecurityContext接口的实例通过SecurityContextHolder的静态方法getContext()获取。
通过SecurityContext可以获取到Authentication接口的实例,而通过Authentication接口可以获取到:
principal:主角,通常是一个UserDetails接口的实例,而默认就是User对象。
credentials:凭证,通常是密码。
authorities:用户拥有的角色列表。
details:WebAuthenticationDetails,包含IP地址和Session ID等信息。
一个典型的用于展示上述用户登录信息的代码如下:
@Controller @RequestMapping("/home") public class HomeController { @RequestMapping("/") public ModelAndView index(){ ModelAndView mv = new ModelAndView(); mv.addObject("message", "Hello,welcome!"); SecurityContext sc = SecurityContextHolder.getContext(); mv.addObject("sc", sc); Object principal = sc.getAuthentication().getPrincipal(); if(principal instanceof UserDetails){ UserDetails userDetails = (UserDetails)principal; mv.addObject("userDetails", userDetails); for(GrantedAuthority authority :userDetails.getAuthorities()){ System.out.println(authority.getAuthority() +" , " + authority.getClass().getCanonicalName()); } } else { String username = (String)principal.toString(); mv.addObject("username", username); } mv.setViewName("home/index"); return mv; } }
jsp页面如下:
<c:if test="${username!=null }"> <p>Username:${username}</p> </c:if> <p> <br />SecurityContext: ${sc.getClass()} <br />Authentication: ${sc.authentication.getClass()} <br />Credentials: ${sc.authentication.credentials} <br />Details: ${sc.authentication.details} </p> <p> <c:if test="${userDetails!=null }"> UserDetails: ${userDetails.getClass()} <table> <tr><td>username</td><td>${userDetails.username }</td></tr> <tr><td>password</td><td>${userDetails.password }</td></tr> </table> Authorities: ${userDetails.authorities } <ul> <c:forEach var="item" items="${userDetails.authorities}" varStatus="index" > <li>${index.index}/${index.count}:${item.authority},${item.getClass()}</li> </c:forEach> </ul> </c:if>
运行结果如下:
SecurityContext: class org.springframework.security.core.context.SecurityContextImpl
Authentication: class org.springframework.security.authentication.UsernamePasswordAuthenticationToken
Credentials:
Details: org.sprin[email protected]b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: DE77CC038C592F5C301C605654436BEE
UserDetails: class org.springframework.security.core.userdetails.User
username zhangsan
password
Authorities: [ROLE_TEST, ROLE_TEST2, ROLE_USER]
0/1:ROLE_TEST,class org.springframework.security.core.authority.SimpleGrantedAuthority
1/2:ROLE_TEST2,class org.springframework.security.core.authority.SimpleGrantedAuthority
2/3:ROLE_USER,class org.springframework.security.core.authority.SimpleGrantedAuthority