You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.6.*禁用休假员工账号实现方案及代码示例求助

Spring Boot 2.6.* 禁用员工账号实现方案

核心思路

禁用账号的关键是让Spring Security识别用户的启用状态,通过UserDetails接口的isEnabled()方法控制认证流程:当用户被标记为禁用时,认证环节会直接拒绝登录请求。

完整可运行代码示例

1. 用户实体类(实现UserDetails)

创建包含启用状态的用户类,实现Spring Security的UserDetails接口,重写核心方法:

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

public class EmployeeUser implements UserDetails {
    private String username;
    private String password;
    private boolean enabled; // 账号启用状态:false=禁用,true=正常
    private String role;

    public EmployeeUser(String username, String password, boolean enabled, String role) {
        this.username = username;
        this.password = password;
        this.enabled = enabled;
        this.role = role;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(new SimpleGrantedAuthority(role));
    }

    @Override
    public String getPassword() {
        return password;
    }

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

    @Override
    public boolean isAccountNonExpired() {
        return true; // 示例默认账号不过期,可按需调整
    }

    @Override
    public boolean isAccountNonLocked() {
        return true; // 示例默认账号不锁定,可按需调整
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true; // 示例默认凭证不过期,可按需调整
    }

    @Override
    public boolean isEnabled() {
        return enabled; // 核心:返回账号启用状态
    }
}

2. UserDetailsService实现类

负责加载用户信息,模拟从数据库获取数据,将休年假员工的enabled设为false:

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class EmployeeUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟数据库查询:zhangsan为休年假员工,禁用账号
        if ("zhangsan".equals(username)) {
            String encodedPassword = new BCryptPasswordEncoder().encode("123456");
            return new EmployeeUser("zhangsan", encodedPassword, false, "ROLE_EMPLOYEE");
        }
        // lisi为正常在职员工,账号启用
        else if ("lisi".equals(username)) {
            String encodedPassword = new BCryptPasswordEncoder().encode("123456");
            return new EmployeeUser("lisi", encodedPassword, true, "ROLE_EMPLOYEE");
        }
        throw new UsernameNotFoundException("用户不存在: " + username);
    }
}

3. Spring Security配置类

继承WebSecurityConfigurerAdapter,配置认证规则与密码编码器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private EmployeeUserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin() // 启用默认表单登录
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
}

4. 测试控制器

创建简单接口验证登录效果:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/hello")
    public String hello() {
        return "登录成功,访问受保护资源";
    }
}

验证效果

  • 使用lisi/123456登录:可正常访问/hello接口
  • 使用zhangsan/123456登录:Spring Security会自动拒绝,默认表单页面会提示账号禁用错误

实际业务扩展建议

  • 生产环境中,用户的启用状态应存储在数据库,通过后台管理接口修改enabled字段值
  • 如需自定义禁用提示信息,可实现AuthenticationFailureHandler处理认证失败逻辑

内容的提问来源于stack exchange,提问作者dbarasuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:55:17