现在的位置: 首页 > 综合 > 正文

java shiro realm 示例一则带加盐

2014年01月02日 ⁄ 综合 ⁄ 共 1257字 ⁄ 字号 评论关闭
public class UsernamePasswordRealm extends AuthorizingRealm {

	public UsernamePasswordRealm() {
		setName("usernamePasswordRealm");
		HashedCredentialsMatcher hcm = new HashedCredentialsMatcher();
		
		//使用SHA-512 加密
		hcm.setHashAlgorithmName(Sha512Hash.ALGORITHM_NAME);
		setCredentialsMatcher(hcm);
	}

	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		try {
			//账户的获取
			Account account = userDao.findByUsername(token.getUsername());
			
			if (account != null) {
				SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
						account.getId(), account.getPassword(), getName());
				//设置加盐,以用户编号加盐,UserID最好以UUID,保证username可改且每个盐值都唯一
				info.setCredentialsSalt(ByteSource.Util.bytes(account.getId()));
				return info;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userId = (String) principals.fromRealm(getName()).iterator()
				.next();
		try {
			Account user = userDao.findById(userId);
			if (user != null) {
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				//*** 赋权操作
				
				.....
				
				///
				return info;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}

账户存储段

//使用加盐,并使用id作为盐值 后面toHex 等效于toString
		this.password = new Sha512Hash(password,this.getId()).toHex();

抱歉!评论已关闭.