页面获取Spring Security登录用户

Web 发表评论

1.在session中取得spring security的登录用户名如下:

[html] view
plain
 copy

  1. ${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}  

       spring security 把SPRING_SECURITY_CONTEXT 放入了session 没有直接把username 放进去。下面一段代码主要描述的是session中的存的变量,

存跳转时候的URLsession {SPRING_SECURITY_SAVED_REQUEST_KEY=SavedRequest[http://localhost:8080/AVerPortal/resourceAction/resourceIndex.action]}
存的是登录成功时候session中存的信息:

        session {SPRING_SECURITY_CONTEXT=org.springframework.security.context.SecurityContextImpl@87b16984: Authentication: org.springframework.security.providers.cas.CasAuthenticationToken@87b16984: Principal: com.avi.casExtends.UserInfo@ff631d80:
Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails@12afc:
RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: org.jasig.cas.client.validation.AssertionImpl@661a11 Credentials (Service/Proxy Ticket): ST-3-1lX3acgZ6HNgmhvjXuxB-cas, userId=2, userName=test}

2.在页面端用tag获取:

[html] view
plain
 copy

  1. <%@ taglib prefix=‘security’ uri=‘http://www.springframework.org/security/tags’%>  
  2.   
  3. <security:authentication property=“principal.username”></security:authentication>   

或者

[html] view
plain
 copy

  1. <security:authorize ifAllGranted=“ROLE_ADMIN”>  
  2.   
  3.  <security:authentication property=“principal.username”></security:authentication>   
  4.   
  5. </security:authorize>  

或者取session中的值:

[html] view
plain
 copy

  1. ${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}  

3.在后台获取

[html] view
plain
 copy

  1. UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  
  2.     .getAuthentication()  
  3.     .getPrincipal();  
  4.   
  5. userDetails.getUsername()  


 

      如果想要获取更多的信息:得扩展userDetails的默认实现类user类和UserDetailsService接口

     由于springsecurity是把整个user信息放入session中的即:session.SPRING_SECURITY_CONTEXT.authentication.principal。这个就是代表着user对象。

下一篇:

发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *