一.创建

  需要在之前SpringSecurity的基础上添加数据库依赖

二.根据数据库创建用户角色类和用户实体类

  角色类

public class Role {  private Long id;
    private String name;
    private String nameZh;
    //省略 getter/setter
}

  用户实体类

public class User implements UserDetails {
    private Long id;
    private String username;
    private String password;
    private boolean accountNonExpired;    //账户是否没有过期
    private boolean accountNonLocked;     //账号是否没有被锁
    private boolean credentialsNonExpired;   //密码是否没有过期
    private boolean enabled;                //账号是否可用
    @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
    private List<Role> roles;     //User 和 Role 是多对多关系,用一个 @ManyToMany 注解来描述。
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
    @Override
    public String getPassword() {
        return password;
    }

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

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
    //省略其他 get/set 方法
}

 

三.使用

  

@Service
public class SsoUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;    //使用mybatis操作数据库
   
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
       
        User user= userMapper.loadUserByName(name);
        if (user== null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        return user;
    }
}

 

四.配置

  1.application.properties 中配置一下数据库

  2.在继承了 WebSecurityConfigurerAdapter类的类中添加如下代码

@Autowired
UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService);
}

 

posted on 2020-04-26 14:49  印记XP  阅读(874)  评论(0编辑  收藏  举报