天工开物征服Springweb后端

Spring Security 获取当前用户

2017-03-02  本文已影响712人  孙亖

页面

如果只是想从页面上显示当前登陆的用户名,可以直接使用Spring Security提供的taglib。

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<div>username : <sec:authentication property="name"/></div>  

<sec:authentication property="name" var="a_name"/>
<sec:authentication property="principal.username" />
<sec:authentication property="principal.enabled" />
<sec:authentication property="principal.accountNonLocked" />  

代码获取用户对象

如果想在程序中获得当前登陆用户对应的对象。

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();        

代码获取权限

如果想获得当前登陆用户所拥有的所有权限。

GrantedAuthority[] authorities = userDetails.getAuthorities();
上一篇 下一篇

猜你喜欢

热点阅读