簡體   English   中英

如何在 Spring Boot Security 中啟用或禁用用戶

[英]How to enable or disable user in Spring Boot Security

我正在為我的 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 + "]";
    }




}

這是我的自定義用戶詳細信息服務

@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);
    }

}

當前自定義 UserDetails 服務檢查用戶名是否存在,如果未找到則拋出異常,我想檢查用戶是否已啟用,以便我也可以設置 isenabled false 以停用用戶。

Just Check for is enabled in loadByUsername method,Further you can activate and deactivate accordingly.我希望它有幫助

@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");
            }

    }

更好的方法是使用org.springframework.security.core.userdetails.UserDetails實現您的User實體並覆蓋各種方法,例如

@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 會根據isEnabled()結果自動給出org.springframework.security.authentication.DisabledException: User is disabled異常。

如果要在數據庫中保留啟用或鎖定狀態,則需要將鎖定和啟用字段的 getter 從 User 模型實例傳遞到 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); 我認為這正是您要尋找的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM