第六章 Realm及相关对象(一) Realm

一、Realm

1. 定义实体及关系

即用户-角色之间是多对多关系,角色-权限之间是多对多关系;且用户和权限之间通过角色建立关系;在系统中验证时通过权限验证,角色只是权限集合,即所谓的显示角色;其实权限应该对应到资源(如菜单、URL、页面按钮、Java 方法等)中,即应该将权限字符串存储到资源实体中,但是目前为了简单化,直接提取一个权限表,【综合示例】部分会使用完整的表结构。

用户实体包括:编号(id)、用户名(username)、密码(password)、盐(salt)、是否锁定(locked);是否锁定用于封禁用户使用,其实最好使用Enum 字段存储,可以实现更复杂的用户状态实现。

角色实体包括:、编号(id)、角色标识符(role)、描述(description)、是否可用(available);其中角色标识符用于在程序中进行隐式角色判断的,描述用于以后再前台界面显示的、是否可用表示角色当前是否激活。

权限实体包括:编号(id)、权限标识符(permission)、描述(description)、是否可用(available);含义和角色实体类似不再阐述。

另外还有两个关系实体:用户-角色实体(用户编号、角色编号,且组合为复合主键);角色-权限实体(角色编号、权限编号,且组合为复合主键)。

2. 环境准备

为了方便数据库操作,使用了“org.springframework: spring-jdbc: 4.0.0.RELEASE”依赖,虽然是spring4版本的,但使用上和spring3 无区别。其他依赖请参考源码的pom.xml。

3. 定义Service及Dao

为了实的简单性,只实现必须的功能,其他的可以自己实现即可。

public interface PermissionService {
	public Permission createPermission(Permission permission);
	public void deletePermission(Long permissionId);
}

实现基本的创建/删除权限。

public interface RoleService {
	public Role createRole(Role role);
	public void deleteRole(Long roleId);
	//添加角色-权限之间关系
	public void correlationPermissions(Long roleId, Long... permissionIds);
	//移除角色-权限之间关系
	public void uncorrelationPermissions(Long roleId, Long... permissionIds);//
}

相对于PermissionService 多了关联/移除关联角色-权限功能。

public interface UserService {
	public User createUser(User user); //创建账户
	public void changePassword(Long userId, String newPassword);//修改密码
	public void correlationRoles(Long userId, Long... roleIds); //添加用户-角色关系
	public void uncorrelationRoles(Long userId, Long... roleIds);// 移除用户-角色关系
	public User findByUsername(String username);// 根据用户名查找用户
	public Set<String> findRoles(String username);// 根据用户名查找其角色
	public Set<String> findPermissions(String username); //根据用户名查找其权限
}

此处使用findByUsername、findRoles及findPermissions来查找用户名对应的帐号、角色及权限信息。之后的Realm就使用这些方法来查找相关信息。

public User createUser(User user) {
	//加密密码
	passwordHelper.encryptPassword(user);
	return userDao.createUser(user);
}
public void changePassword(Long userId, String newPassword) {
	User user =userDao.findOne(userId);
	user.setPassword(newPassword);
	passwordHelper.encryptPassword(user);
	userDao.updateUser(user);
}

在创建账户及修改密码时直接把生成密码操作委托给PasswordHelper。

public class PasswordHelper {
	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "md5";
	private final int hashIterations = 2;
	public void encryptPassword(User user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		String newPassword = new SimpleHash(
			algorithmName,
			user.getPassword(),
			ByteSource.Util.bytes(user.getCredentialsSalt()),
			hashIterations).toHex();
		user.setPassword(newPassword);
	}
}

之后的CredentialsMatcher需要和此处加密的算法一样。user.getCredentialsSalt()辅助方法返回username+salt。

为 了 节省篇幅, 对于DAO/Service 的接口及实现, 具体请参考源码com.github.zhangkaitao.shiro.chapter6 。另外请参考Service 层的测试用例com.github.zhangkaitao.shiro.chapter6.service.ServiceTest。

4. 定义Realm

RetryLimitHashedCredentialsMatcher

和第五章一样。

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher{
	private Ehcache passwordRetryCache;
	
	public RetryLimitHashedCredentialsMatcher() {
		CacheManager cacheManager = CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("chapter6/ini/ehcache.xml"));
		passwordRetryCache = cacheManager.getCache("passwordRetryCache");
	}
	public boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info) {
		String username = (String) token.getPrincipal();
		Element element = passwordRetryCache.get(username);
		if(element == null){
			element = new Element(username,new AtomicInteger(0));
			passwordRetryCache.put(element);
		}
		AtomicInteger retryCount = (AtomicInteger) element.getObjectValue();
		if(retryCount.incrementAndGet()>5){
			//if retry count > 5 throw
			throw new ExcessiveAttemptsException();
		}
		
		boolean matches = super.doCredentialsMatch(token, info);
		if(matches){
			//clear retry count
			passwordRetryCache.remove(username);
		}
		return matches;
	}
}

UserRealm

public class UserRealm extends AuthorizingRealm {
	private UserService userService = new UserServiceImpl();
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(userService.findRoles(username));
		authorizationInfo.setStringPermissions(userService.findPermissions(username));
		return authorizationInfo;
	}
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		User user = userService.findByUsername(username);
		if(user == null) {
			throw new UnknownAccountException();//没找到帐号
		}
		if(Boolean.TRUE.equals(user.getLocked())) {
			throw new LockedAccountException(); //帐号锁定
		}
		//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
			user.getUsername(), //用户名
			user.getPassword(), //密码
			ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
			getName() //realm name
		);
		return authenticationInfo;
	}
}

1)UserRealm 父类AuthorizingRealm 将获取Subject 相关信息分成两步:获取身份验证信息(doGetAuthenticationInfo)及授权信息(doGetAuthorizationInfo);

2)doGetAuthenticationInfo 获取身份验证相关信息:首先根据传入的用户名获取User 信息;然后如果user 为空,那么抛出没找到帐号异常UnknownAccountException;如果user找到但锁定了抛出锁定异常LockedAccountException;最后生成AuthenticationInfo 信息,交给间接父类AuthenticatingRealm使用CredentialsMatcher进行判断密码是否匹配,如果不匹配将抛出密码错误异常IncorrectCredentialsException;另外如果密码重试次数太多将抛出超出重试次数异常ExcessiveAttemptsException;在组装SimpleAuthenticationInfo 信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt),CredentialsMatcher使用盐加密传入的明文密码和此处的密文密码进行匹配。

3)doGetAuthorizationInfo获取授权信息:PrincipalCollection是一个身份集合,因为我们现在就一个Realm,所以直接调用getPrimaryPrincipal得到之前传入的用户名即可;然后根据用户名调用UserService接口获取角色及权限信息。

5. 测试用例

为了节省篇幅,请参考测试用例com.github.zhangkaitao.shiro.chapter6.realm.UserRealmTest。包含了:登录成功、用户名错误、密码错误、密码超出重试次数、有/没有角色、有/没有权限的测试。


完整例子见我的资源库下载:

ShiroDemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值