如何在Spring Boot Security中启用或禁用用户

时间:2018-12-22 05:39:05

标签: java spring spring-boot

我正在为我的spring boot应用程序使用spring security,这是我的用户实体

@Document(collection = "users")
public class User {
    @Id
    private String id;

    private String username;


    private String isactive;
    private String type;
    private String date;

    private String registrarid;
    private String registrartype;

    public String getRegistrarid() {
        return registrarid;
    }
    public void setRegistrarid(String registrarid) {
        this.registrarid = registrarid;
    }
    public String getRegistrartype() {
        return registrartype;
    }
    public void setRegistrartype(String registrartype) {
        this.registrartype = registrartype;
    }
    public String getIsactive() {
        return isactive;
    }
    public void setIsactive(String isactive) {
        this.isactive = isactive;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(balance);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((date == null) ? 0 : date.hashCode());
        result = prime * result + (enabled ? 1231 : 1237);
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((isactive == null) ? 0 : isactive.hashCode());
        result = prime * result + ((password == null) ? 0 : password.hashCode());
        result = prime * result + ((registrarid == null) ? 0 : registrarid.hashCode());
        result = prime * result + ((registrartype == null) ? 0 : registrartype.hashCode());
        result = prime * result + ((roles == null) ? 0 : roles.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (Double.doubleToLongBits(balance) != Double.doubleToLongBits(other.balance))
            return false;
        if (date == null) {
            if (other.date != null)
                return false;
        } else if (!date.equals(other.date))
            return false;
        if (enabled != other.enabled)
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (isactive == null) {
            if (other.isactive != null)
                return false;
        } else if (!isactive.equals(other.isactive))
            return false;
        if (password == null) {
            if (other.password != null)
                return false;
        } else if (!password.equals(other.password))
            return false;
        if (registrarid == null) {
            if (other.registrarid != null)
                return false;
        } else if (!registrarid.equals(other.registrarid))
            return false;
        if (registrartype == null) {
            if (other.registrartype != null)
                return false;
        } else if (!registrartype.equals(other.registrartype))
            return false;
        if (roles == null) {
            if (other.roles != null)
                return false;
        } else if (!roles.equals(other.roles))
            return false;
        if (type == null) {
            if (other.type != null)
                return false;
        } else if (!type.equals(other.type))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }

    private double balance;
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }



    private boolean enabled=true;

    @DBRef
    private Set<Role> roles;


    private String password;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isEnabled() {
        return enabled;
    }
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    public Set<Role> getRoles() {
        return roles;
    }
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", isactive=" + isactive + ", type=" + type + ", date="
                + date + ", registrarid=" + registrarid + ", registrartype=" + registrartype + ", balance=" + balance
                + ", enabled=" + enabled + ", roles=" + roles + ", password=" + password + "]";
    }




}

这是我的CustomUser Details服务

@Service
public class CustomUserDetailsService implements UserDetailsService{
    @Autowired
    private UserServiceImpl userservice;

    @Autowired
    private RoleServiceImpl roleservice;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user=userservice.getUserByusername(username);

            if(user != null) {
                List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
                return buildUserForAuthentication(user, authorities);
            } 

            else {
                throw new UsernameNotFoundException("username not found");
            }

    }

    private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
        Set<GrantedAuthority> roles = new HashSet<>();
        userRoles.forEach((role) -> {
            roles.add(new SimpleGrantedAuthority(role.getRole()));
        });

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
        return grantedAuthorities;
    }

    private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }

}

当前Custom UserDetails Service检查用户名是否存在,如果找不到,则会引发异常,我想检查用户是否已启用,以便我也可以将isenabled设置为false来停用用户。

3 个答案:

答案 0 :(得分:5)

更好的方法是使用User来实现您的org.springframework.security.core.userdetails.UserDetails实体 并覆盖各种方法,例如

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

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

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

@Override
public boolean isEnabled() {
    if(this.isactive == null) return false;

    if(!this.isactive.equals("ACTIVE")) return false;

    return true;
}

还根据需要替代其他方法。 Spring Security会根据org.springframework.security.authentication.DisabledException: User is disabled的结果自动给isEnabled()赋予例外。

答案 1 :(得分:0)

在loadByUsername方法中启用了“仅检查”功能,您还可以相应地激活和停用它。希望对您有所帮助

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user=userservice.getUserByusername(username);

            if(user != null && user.isEnabled()) {//here you can check that
                List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
                return buildUserForAuthentication(user, authorities);
            } 

            else {
                throw new UsernameNotFoundException("username not found");
            }

    }

答案 2 :(得分:0)

如果要在数据库中保留已启用或已锁定状态,则需要将用户模型实例中已锁定和已启用字段的获取器传递给UserDetailsImpl构造函数。

首先, authenticationManager的authenticate函数返回以下异常:

  1. DisabledException,如果帐户被禁用
  2. LockedException,如果帐户已锁定
  3. BadCredentialsException,如果提供的凭据不正确

您可能想按照以下步骤做些事情:

try {

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(authreq.getUsername(), authreq.getPassword()));
} catch (BadCredentialsException ex) {
    // do something
} catch (LockedException ex) {
    // do something
} catch (DisabledException ex) {
    // do something
}

然后在UserDetailsImpl中:

public UserDetailsImpl(Integer id, String username, String email, String password,
            Collection<? extends GrantedAuthority> authorities, boolean isEnabled) {
        this.id = id;
        this.username = username;
        this.email = email;
        this.password = password;
        this.authorities = authorities;
        this.isEnabled = isEnabled;
    }

    public static UserDetailsImpl build(User user) {
        List<GrantedAuthority> authorities = user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList());

        return new UserDetailsImpl(user.getId(), user.getUsername(), user.getEmail(), user.getPassword(), authorities,
                user.isIsenabled());
    }

顺便说一句,为了使它起作用,您必须从@Shubh的上一个答案中删除if语句,而应使用以下命令:return buildUserForAuthentication(user, authorities); 我认为这几乎就是您想要的。