一.創建
需要在之前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); }