springboot security (四)返回自定义的用户对象

1. 数据库中的sysuer对象

package com.hanhuide.core.model;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 

* *

* * @author 韩惠德 * @since 2019-11-29 */ @TableName("sys_user") @Data public class SysUser implements Serializable{ private static final long serialVersionUID = 1L; /** * 用户ID */ @TableId(value = "USER_ID", type = IdType.AUTO) private Long userId; /** * 用户名 */ @TableField("USERNAME") private String username; /** * 密码 */ @TableField("PASSWORD") private String password; /** * 部门ID */ @TableField("DEPT_ID") private Long deptId; /** * 邮箱 */ @TableField("EMAIL") private String email; /** * 联系电话 */ @TableField("MOBILE") private String mobile; /** * 状态 0锁定 1有效 */ @TableField("STATUS") private String status; /** * 创建时间 */ @TableField("CREATE_TIME") private Date createTime; /** * 修改时间 */ @TableField("MODIFY_TIME") private Date modifyTime; /** * 最近访问时间 */ @TableField("LAST_LOGIN_TIME") private Date lastLoginTime; /** * 性别 0男 1女 2保密 */ @TableField("SSEX") private String ssex; /** * 描述 */ @TableField("DESCRIPTION") private String description; /** * 用户头像 */ @TableField("AVATAR") private String avatar; private List childRole; public void setAvatar(String avatar) { this.avatar = avatar; } public static final String USER_ID = "USER_ID"; public static final String USERNAME = "USERNAME"; public static final String PASSWORD = "PASSWORD"; public static final String DEPT_ID = "DEPT_ID"; public static final String EMAIL = "EMAIL"; public static final String MOBILE = "MOBILE"; public static final String STATUS = "STATUS"; public static final String CREATE_TIME = "CREATE_TIME"; public static final String MODIFY_TIME = "MODIFY_TIME"; public static final String LAST_LOGIN_TIME = "LAST_LOGIN_TIME"; public static final String SSEX = "SSEX"; public static final String DESCRIPTION = "DESCRIPTION"; public static final String AVATAR = "AVATAR"; @Override public String toString() { return "SysUser{" + "userId=" + userId + ", username=" + username + ", password=" + password + ", deptId=" + deptId + ", email=" + email + ", mobile=" + mobile + ", status=" + status + ", createTime=" + createTime + ", modifyTime=" + modifyTime + ", lastLoginTime=" + lastLoginTime + ", ssex=" + ssex + ", description=" + description + ", avatar=" + avatar + "}"; } }

2. 新建返回的user对象 继承sysuser 实现 security UserDetails

package com.hanhuide.core.model;

import com.hanhuide.core.model.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * CustomerUserDetails
 *
 * @author zgd
 * @date 2019/7/17 15:29
 */
public class CustomerUserDetails extends SysUser implements UserDetails {

    private Collection authorities;

    public CustomerUserDetails(SysUser user){
        this.setUsername(user.getUsername());
        this.setPassword(user.getPassword());
        this.setStatus(user.getStatus());
    }

    public void setAuthorities(Collection authorities) {
        this.authorities = authorities;
    }

    /**
     * 添加用户拥有的权限和角色
     * @return
     */
    @Override
    public Collection getAuthorities() {
        return this.authorities;
    }

    /**
     * 账户是否过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否禁用
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return  true;
    }

    /**
     * 密码是否过期
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}

3. 编辑CustomUserDetailsService
package com.hanhuide.core.service.impl;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.hanhuide.core.model.CustomerUserDetails;
import com.hanhuide.core.model.SysRole;
import com.hanhuide.core.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @program: maven
 * @description:用户认证、权限
 * @author: 韩惠德
 * @create: 2019-12-26 11:59
 * @version: 1.0
 **/
@Service("userDetailsService")
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserServiceImpl userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取用户信息
        SysUser user = new SysUser();
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        user.setUsername("测试");
        SysRole sysRole = new SysRole();
        sysRole.setRoleName("管理员");
        List list = new ArrayList<>();
        list.add(sysRole);
        user.setChildRole(list);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        CustomerUserDetails userDetails = new CustomerUserDetails(user);
        Collection authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        if (CollectionUtils.isNotEmpty(user.getChildRole())) {
            user.getChildRole().forEach(r -> authorities.add(new SimpleGrantedAuthority(r.getRoleName())));
        }
        userDetails.setAuthorities(authorities);
        log.info("authorities:{}", authorities);
        //返回的是我们自己定义的UserDetail
        return userDetails;//密码必须加密
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("hanhuide");
        System.out.println(password);
    }
}

登录 用户名(测试)密码(123456)

你可能感兴趣的:(security,自定义返回结果,springboot)