SpringSecurity设置用户状态
作者:互联网
用户认证业务里,我们封装User对象时,选择了三个构造参数的构造方法,其实还有另一个构造方法,源码如下:
public User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { if (username != null && !"".equals(username) && password != null) { this.username = username; this.password = password; this.enabled = enabled; this.accountNonExpired = accountNonExpired; this.credentialsNonExpired = credentialsNonExpired; this.accountNonLocked = accountNonLocked; this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities)); } else { throw new IllegalArgumentException("Cannot pass null or empty values to constructor"); } }
可以看到,这个构造方法里多了四个布尔类型的构造参数,其实我们使用的三个构造参数的构造方法里这四个布尔值默认都被赋值为了true,那么这四个布尔值到底是何意思呢?
boolean enabled 是否可用
boolean accountNonExpired 账户是否失效
boolean credentialsNonExpired 密码是否失效
boolean accountNonLocked 账户是否锁定
判断认证用户的状态:
这四个参数必须同时为true认证才可以通过,修改认证业务代码:
/** * 认证业务 * @param username 用户在浏览器输入的用户名 * @return UserDetails 是springSecurity自己的用户对象 * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { // 根据用户名做查询 SysUser user = userDao.findByName(username); if (user == null) { //若用户名不对,直接返回null,表示认证失败。 return null; } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); List<SysRole> roles = user.getRoles(); for (SysRole role : roles) { authorities.add(new SimpleGrantedAuthority(role.getRoleName())); } //最终需要返回一个SpringSecurity的UserDetails对象,{noop}表示不加密认证。 // UserDetails userDetails = new User(user.getUsername(), "{noop}" + user.getPassword(), authorities); // UserDetails userDetails = new User(user.getUsername(), user.getPassword(), authorities); UserDetails userDetails = new User(user.getUsername(), user.getPassword(), user.getStatus() == 1, true, true, true, authorities); return userDetails; } catch (Exception e) { e.printStackTrace(); // springSecurity内部认为返回null就是认证失败 return null; } }
此时,只有用户状态为1的用户才能成功通过认证!
标签:username,用户,SpringSecurity,boolean,user,设置,authorities,认证,null 来源: https://www.cnblogs.com/roadlandscape/p/12482281.html