spring security获取当前用户信息

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/lwwl12/article/details/81289973

(一) 在当前页面显示

1. maven引入

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

2. 页面展示(thymeleaf)

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <meta content="text/html;charset=UTF-8"/>
        <title sec:authentication="name"></title> <!-- 获得当前用户的用户名 -->
    </head>
    <body>

        <!–匿名–>
        <div sec:authorize=“isAnonymous()”>
            未登录,点击 <a th:href=“@{/login}”>登录</a>
        </div>
        <!–登录–>
        <div sec:authorize=“isAuthenticated()”>
            <p>已登录</p>
            <p>登录名:<span sec:authentication=“name”></span></p>
            <p>角色:<span sec:authentication=“principal.authorities”></span></p>
            <p>Username:<span sec:authentication=“principal.username”></span></p>
            <p>Password:<span sec:authentication=“principal.password”></span></p>

            <!--以下属性需自定义类继承UserDetails后新增-->
            <p>Email :<span sec:authentication=“principal.email”></span></p>
            <p>Name:<span sec:authentication=“principal.name”></span></p>
            <p>Status:<span sec:authentication=“principal.status”></span></p>

            <p>拥有的角色:
            <span sec:authorize=“hasRole(‘ROLE_ADMIN’)”>管理员</span>
            <span sec:authorize=“hasRole(‘ROLE_USER’)”>用户</span>
        </p>
    </div>

    </body>
</html>

(二) 在代码中使用

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

(三) 继承UserDetails自定义用户信息类

public class UserDTO implements UserDetails {

    public UserDTO(int userId, String userName,String password,String salt,String name,boolean deleted,boolean lockout,boolean active, int tenantId,int organizationId,Collection<? extends GrantedAuthority> authorities) {

        this.userId=userId;
        this.userName=userName;
        this.password=password;
        this.salt=salt;
        this.name=name;
        this.deleted=deleted;
        this.locked=lockout;
        this.active=active;
        this.tenantId=tenantId;
        this.organizationUnitId=organizationId;
        this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));

    }

    private final String userName;
    private final String password;
    private final String name;
    private final int userId;
    private final boolean deleted;
    private final boolean locked;
    private final boolean active;
    private final String salt;
    private final int tenantId;
    private final int organizationUnitId;
    private final Set<GrantedAuthority> authorities;

    public int getOrganizationUnitId() {
        return organizationUnitId;
    }

    public String getUserName() {
        return userName;
    }

    public String getName() {
        return name;
    }

    public int getUserId() {
        return userId;
    }

    public boolean isDeleted() {
        return deleted;
    }

    public boolean isLocked() {
        return locked;
    }

    public boolean isActive() {
        return active;
    }

    public String getSalt() {
        return salt;
    }

    public int getTenantId() {
        return tenantId;
    }

    private static SortedSet<GrantedAuthority> sortAuthorities(
            Collection<? extends GrantedAuthority> authorities) {
        Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
        // Ensure array iteration order is predictable (as per
        // UserDetails.getAuthorities() contract and SEC-717)
        SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<>(
                new UserDTO.AuthorityComparator());

        for (GrantedAuthority grantedAuthority : authorities) {
            Assert.notNull(grantedAuthority,
                    "GrantedAuthority list cannot contain any null elements");
            sortedAuthorities.add(grantedAuthority);
        }

        return sortedAuthorities;
    }

    private static class AuthorityComparator implements Comparator<GrantedAuthority>,
            Serializable {
        private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

        public int compare(GrantedAuthority g1, GrantedAuthority g2) {
            // Neither should ever be null as each entry is checked before adding it to
            // the set.
            // If the authority is null, it is a custom authority and should precede
            // others.
            if (g2.getAuthority() == null) {
                return -1;
            }

            if (g1.getAuthority() == null) {
                return 1;
            }

            return g1.getAuthority().compareTo(g2.getAuthority());
        }
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return userName;
    }

    // 账号未失效 deleted == 1 ?
    @Override
    public boolean isAccountNonExpired() {
        return !deleted;
    }

    // 账号未锁定 lockout == 1 ?
    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    // 凭证未失效
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 可用 active == 1 ?
    @Override
    public boolean isEnabled() {
        return active;
    }
}

猜你喜欢

转载自blog.csdn.net/lwwl12/article/details/81289973