Skip to content

B、接入用户数据

wangjie edited this page Dec 24, 2019 · 2 revisions

支持从数据库、文件、LDAP、远程服务等渠道获取用户(认证)数据

实现Account接口:

@TableName("t_user")
public class UserEntity implements Account{
	private static final long serialVersionUID = 1L;
	// 状态-删除
	public final static Short USER_STATUS_OK = 1;
	// 状态-锁定
	public final static Short USER_STATUS_LOCKED = 2;
	// 状态-删除
	private final static Short USER_STATUS_DELETED = 9;

	private String id;// 主键
	private String account; // 账号
	private String password; // 密码
        private String userName; // 用户姓名
        private Integer status;//状态    1:正常、2:锁定、9:删除
        @Override
	public String getAccount() {
		return account;
	}
        @Override
	public String getPassword() {
		return password;
	} 

        //省略其余 getters and setters ... ...
}

实现ShiroAccountProvider接口:

@Service
public class AccountProviderImpl implements ShiroAccountProvider {

	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;
        /** 
         * 加载用户信息
         */
	@Override
	public Account loadAccount(String account) throws AuthenticationException {
		UserEntity user = userService.getByAccount(account);
		// 用户不存在
		if(null == user){
			throw new AuthenticationException("账号或密码错误");
		}
		// 对账号做检查
		// 当账号异常,如账号被锁定、被禁用等等需要限制登陆,直接抛出AuthenticationException即可
		if(UserEntity.USER_STATUS_LOCKED == user.getStatus()){
			throw new AuthenticationException("账号已被锁定,请联系系统管理员");
		}
		return user;
	}
	
	/** 
	 * 加载用户持有的角色列表
	 */
	@Override
	public Set<String> loadRoles(String account) {
		return Sets.newHashSet(userRoleService.listUserRoles(account));
	}
	
	/**
	 * 加载用户的权限列表
	 * 系统安全策略是基于角色的权限访问控制(RBAC),故权限列表为空
	 */ 
	@Override
	public Set<String> loadPermissions(String account) {
		return null;
	}
}

配置ShiroCustomizer

@Configuration
public class ApplicationConfig{

	// 账号数据提供服务
	@Autowired
	private AccountProviderImpl accountProviderImpl;

	@Bean
	public ShiroCustomizer shiroCustomizer() {
		ShiroCustomizer customizer = new ShiroCustomizer();
		// 设置账号数据提供服务
		customizer.setShiroAccountProvider(accountProviderImpl); 
		return customizer;
	}
}