6.1 Realm
【2.5 Realm】及【3.5 Authorizer】部分都已经详细介绍过Realm了,接下来再来看一下通常真实环境下的Realm如何实现。git
1、定义实体及关系github
即用户-角色之间是多对多关系,角色-权限之间是多对多关系;且用户和权限之间经过角色创建关系;在系统中验证时经过权限验证,角色只是权限集合,即所谓的显示角色;其实权限应该对应到资源(如菜单、URL、页面按钮、Java方法等)中,即应该将权限字符串存储到资源实体中,可是目前为了简单化,直接提取一个权限表,【综合示例】部分会使用完整的表结构。算法
用户实体包括:编号(id)、用户名(username)、密码(password)、盐(salt)、是否锁定(locked);是否锁定用于封禁用户使用,其实最好使用Enum字段存储,能够实现更复杂的用户状态实现。spring
角色实体包括:、编号(id)、角色标识符(role)、描述(description)、是否可用(available);其中角色标识符用于在程序中进行隐式角色判断的,描述用于之后再前台界面显示的、是否可用表示角色当前是否激活。sql
权限实体包括:编号(id)、权限标识符(permission)、描述(description)、是否可用(available);含义和角色实体相似再也不阐述。数据库
另外还有两个关系实体:用户-角色实体(用户编号、角色编号,且组合为复合主键);角色-权限实体(角色编号、权限编号,且组合为复合主键)。安全
sql及实体请参考源代码中的sql\shiro.sql 和 com.github.zhangkaitao.shiro.chapter6.entity对应的实体。多线程
2、环境准备dom
为了方便数据库操做,使用了“org.springframework: spring-jdbc: 4.0.0.RELEASE”依赖,虽然是spring4版本的,但使用上和spring3无区别。其余依赖请参考源码的pom.xml。ide
3、定义Service及Dao
为了实现的简单性,只实现必须的功能,其余的能够本身实现便可。
PermissionService
Java代码
- public interface PermissionService {
- public Permission createPermission(Permission permission);
- public void deletePermission(Long permissionId);
- }
实现基本的建立/删除权限。
RoleService
Java代码
- 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多了关联/移除关联角色-权限功能。
UserService
Java代码
- 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就使用这些方法来查找相关信息。
UserServiceImpl
Java代码
- 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。
PasswordHelper
Java代码
- 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
和第五章的同样,在此就不罗列代码了,请参考源码com.github.zhangkaitao.shiro.chapter6.credentials.RetryLimitHashedCredentialsMatcher。
UserRealm
另外请参考Service层的测试用例com.github.zhangkaitao.shiro.chapter6.service.ServiceTest。
Java代码
- 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。包含了:登陆成功、用户名错误、密码错误、密码超出重试次数、有/没有角色、有/没有权限的测试。
6.2 AuthenticationToken
AuthenticationToken用于收集用户提交的身份(如用户名)及凭据(如密码):
Java代码
- public interface AuthenticationToken extends Serializable {
- Object getPrincipal(); //身份
- Object getCredentials(); //凭据
- }
扩展接口RememberMeAuthenticationToken:提供了“boolean isRememberMe()”现“记住我”的功能;
扩展接口是HostAuthenticationToken:提供了“String getHost()”方法用于获取用户“主机”的功能。
Shiro提供了一个直接拿来用的UsernamePasswordToken,用于实现用户名/密码Token组,另外其实现了RememberMeAuthenticationToken和HostAuthenticationToken,能够实现记住我及主机验证的支持。
6.3 AuthenticationInfo
AuthenticationInfo有两个做用:
一、若是Realm是AuthenticatingRealm子类,则提供给AuthenticatingRealm内部使用的CredentialsMatcher进行凭据验证;(若是没有继承它须要在本身的Realm中本身实现验证);
二、提供给SecurityManager来建立Subject(提供身份信息);
MergableAuthenticationInfo用于提供在多Realm时合并AuthenticationInfo的功能,主要合并Principal、若是是其余的如credentialsSalt,会用后边的信息覆盖前边的。
好比HashedCredentialsMatcher,在验证时会判断AuthenticationInfo是不是SaltedAuthenticationInfo子类,来获取盐信息。
Account至关于咱们以前的User,SimpleAccount是其一个实现;在IniRealm、PropertiesRealm这种静态建立账号信息的场景中使用,这些Realm直接继承了SimpleAccountRealm,而SimpleAccountRealm提供了相关的API来动态维护SimpleAccount;便可以经过这些API来动态增删改查SimpleAccount;动态增删改查角色/权限信息。及若是您的账号不是特别多,可使用这种方式,具体请参考SimpleAccountRealm Javadoc。
其余状况通常返回SimpleAuthenticationInfo便可。
6.4 PrincipalCollection
由于咱们能够在Shiro中同时配置多个Realm,因此呢身份信息可能就有多个;所以其提供了PrincipalCollection用于聚合这些身份信息:
Java代码
- public interface PrincipalCollection extends Iterable, Serializable {
- Object getPrimaryPrincipal(); //获得主要的身份
- <T> T oneByType(Class<T> type); //根据身份类型获取第一个
- <T> Collection<T> byType(Class<T> type); //根据身份类型获取一组
- List asList(); //转换为List
- Set asSet(); //转换为Set
- Collection fromRealm(String realmName); //根据Realm名字获取
- Set<String> getRealmNames(); //获取全部身份验证经过的Realm名字
- boolean isEmpty(); //判断是否为空
- }
由于PrincipalCollection聚合了多个,此处最须要注意的是getPrimaryPrincipal,若是只有一个Principal那么直接返回便可,若是有多个Principal,则返回第一个(由于内部使用Map存储,因此能够认为是返回任意一个);oneByType / byType根据凭据的类型返回相应的Principal;fromRealm根据Realm名字(每一个Principal都与一个Realm关联)获取相应的Principal。
MutablePrincipalCollection是一个可变的PrincipalCollection接口,即提供了以下可变方法:
Java代码
- public interface MutablePrincipalCollection extends PrincipalCollection {
- void add(Object principal, String realmName); //添加Realm-Principal的关联
- void addAll(Collection principals, String realmName); //添加一组Realm-Principal的关联
- void addAll(PrincipalCollection principals);//添加PrincipalCollection
- void clear();//清空
- }
目前Shiro只提供了一个实现SimplePrincipalCollection,还记得以前的AuthenticationStrategy实现嘛,用于在多Realm时判断是否知足条件的,在大多数实现中(继承了AbstractAuthenticationStrategy)afterAttempt方法会进行AuthenticationInfo(实现了MergableAuthenticationInfo)的merge,好比SimpleAuthenticationInfo会合并多个Principal为一个PrincipalCollection。
对于PrincipalMap是Shiro 1.2中的一个实验品,暂时无用,具体能够参考其Javadoc。接下来经过示例来看看PrincipalCollection。
1、准备三个Realm
MyRealm1
Java代码
- public class MyRealm1 implements Realm {
- @Override
- public String getName() {
- return "a"; //realm name 为 “a”
- }
- //省略supports方法,具体请见源码
- @Override
- public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- return new SimpleAuthenticationInfo(
- "zhang", //身份 字符串类型
- "123", //凭据
- getName() //Realm Name
- );
- }
- }
MyRealm2
和MyRealm1彻底同样,只是Realm名字为b。
MyRealm3
Java代码
- public class MyRealm3 implements Realm {
- @Override
- public String getName() {
- return "c"; //realm name 为 “c”
- }
- //省略supports方法,具体请见源码
- @Override
- public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- User user = new User("zhang", "123");
- return new SimpleAuthenticationInfo(
- user, //身份 User类型
- "123", //凭据
- getName() //Realm Name
- );
- }
- }
和MyRealm1同名,但返回的Principal是User类型。
二、ini配置(shiro-multirealm.ini)
Java代码
- [main]
- realm1=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm1
- realm2=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm2
- realm3=com.github.zhangkaitao.shiro.chapter6.realm.MyRealm3
- securityManager.realms=$realm1,$realm2,$realm3
3、测试用例(com.github.zhangkaitao.shiro.chapter6.realm.PrincialCollectionTest)
由于咱们的Realm中没有进行身份及凭据验证,因此至关于身份验证都是成功的,都将返回:
Java代码
- Object primaryPrincipal1 = subject.getPrincipal();
- PrincipalCollection princialCollection = subject.getPrincipals();
- Object primaryPrincipal2 = princialCollection.getPrimaryPrincipal();
咱们能够直接调用subject.getPrincipal获取PrimaryPrincipal(即所谓的第一个);或者经过getPrincipals获取PrincipalCollection;而后经过其getPrimaryPrincipal获取PrimaryPrincipal。
Java代码
- Set<String> realmNames = princialCollection.getRealmNames();
获取全部身份验证成功的Realm名字。
Java代码
- Set<Object> principals = princialCollection.asSet(); //asList和asSet的结果同样
将身份信息转换为Set/List,即便转换为List,也是先转换为Set再完成的。
Java代码
- Collection<User> users = princialCollection.fromRealm("c");
根据Realm名字获取身份,由于Realm名字能够重复,因此可能多个身份,建议Realm名字尽可能不要重复。
6.4 AuthorizationInfo
AuthorizationInfo用于聚合受权信息的:
Java代码
- public interface AuthorizationInfo extends Serializable {
- Collection<String> getRoles(); //获取角色字符串信息
- Collection<String> getStringPermissions(); //获取权限字符串信息
- Collection<Permission> getObjectPermissions(); //获取Permission对象信息
- }
当咱们使用AuthorizingRealm时,若是身份验证成功,在进行受权时就经过doGetAuthorizationInfo方法获取角色/权限信息用于受权验证。
Shiro提供了一个实现SimpleAuthorizationInfo,大多数时候使用这个便可。
对于Account及SimpleAccount,以前的【6.3 AuthenticationInfo】已经介绍过了,用于SimpleAccountRealm子类,实现动态角色/权限维护的。
6.5 Subject
Subject是Shiro的核心对象,基本全部身份验证、受权都是经过Subject完成。
1、身份信息获取
Java代码
- Object getPrincipal(); //Primary Principal
- PrincipalCollection getPrincipals(); // PrincipalCollection
2、身份验证
Java代码
- void login(AuthenticationToken token) throws AuthenticationException;
- boolean isAuthenticated();
- boolean isRemembered();
经过login登陆,若是登陆失败将抛出相应的AuthenticationException,若是登陆成功调用isAuthenticated就会返回true,即已经经过身份验证;若是isRemembered返回true,表示是经过记住我功能登陆的而不是调用login方法登陆的。isAuthenticated/isRemembered是互斥的,即若是其中一个返回true,另外一个返回false。
3、角色受权验证
Java代码
- boolean hasRole(String roleIdentifier);
- boolean[] hasRoles(List<String> roleIdentifiers);
- boolean hasAllRoles(Collection<String> roleIdentifiers);
- void checkRole(String roleIdentifier) throws AuthorizationException;
- void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException;
- void checkRoles(String... roleIdentifiers) throws AuthorizationException;
hasRole*进行角色验证,验证后返回true/false;而checkRole*验证失败时抛出AuthorizationException异常。
4、权限受权验证
Java代码
- boolean isPermitted(String permission);
- boolean isPermitted(Permission permission);
- boolean[] isPermitted(String... permissions);
- boolean[] isPermitted(List<Permission> permissions);
- boolean isPermittedAll(String... permissions);
- boolean isPermittedAll(Collection<Permission> permissions);
- void checkPermission(String permission) throws AuthorizationException;
- void checkPermission(Permission permission) throws AuthorizationException;
- void checkPermissions(String... permissions) throws AuthorizationException;
- void checkPermissions(Collection<Permission> permissions) throws AuthorizationException;
isPermitted*进行权限验证,验证后返回true/false;而checkPermission*验证失败时抛出AuthorizationException。
5、会话
Java代码
- Session getSession(); //至关于getSession(true)
- Session getSession(boolean create);
相似于Web中的会话。若是登陆成功就至关于创建了会话,接着可使用getSession获取;若是create=false若是没有会话将返回null,而create=true若是没有会话会强制建立一个。
6、退出
Java代码
- void logout();
7、RunAs
Java代码
- void runAs(PrincipalCollection principals) throws NullPointerException, IllegalStateException;
- boolean isRunAs();
- PrincipalCollection getPreviousPrincipals();
- PrincipalCollection releaseRunAs();
RunAs即实现“容许A假设为B身份进行访问”;经过调用subject.runAs(b)进行访问;接着调用subject.getPrincipals将获取到B的身份;此时调用isRunAs将返回true;而a的身份须要经过subject. getPreviousPrincipals获取;若是不须要RunAs了调用subject. releaseRunAs便可。
8、多线程
Java代码
- <V> V execute(Callable<V> callable) throws ExecutionException;
- void execute(Runnable runnable);
- <V> Callable<V> associateWith(Callable<V> callable);
- Runnable associateWith(Runnable runnable);
实现线程之间的Subject传播,由于Subject是线程绑定的;所以在多线程执行中须要传播到相应的线程才能获取到相应的Subject。最简单的办法就是经过execute(runnable/callable实例)直接调用;或者经过associateWith(runnable/callable实例)获得一个包装后的实例;它们都是经过:一、把当前线程的Subject绑定过去;二、在线程执行结束后自动释放。
Subject本身不会实现相应的身份验证/受权逻辑,而是经过DelegatingSubject委托给SecurityManager实现;及能够理解为Subject是一个面门。
对于Subject的构建通常不必咱们去建立;通常经过SecurityUtils.getSubject()获取:
Java代码
- public static Subject getSubject() {
- Subject subject = ThreadContext.getSubject();
- if (subject == null) {
- subject = (new Subject.Builder()).buildSubject();
- ThreadContext.bind(subject);
- }
- return subject;
- }
即首先查看当前线程是否绑定了Subject,若是没有经过Subject.Builder构建一个而后绑定到现场返回。
若是想自定义建立,能够经过:
Java代码
- new Subject.Builder().principals(身份).authenticated(true/false).buildSubject()
这种能够建立相应的Subject实例了,而后本身绑定到线程便可。在new Builder()时若是没有传入SecurityManager,自动调用SecurityUtils.getSecurityManager获取;也能够本身传入一个实例。
对于Subject咱们通常这么使用:
一、身份验证(login)
二、受权(hasRole*/isPermitted*或checkRole*/checkPermission*)
三、将相应的数据存储到会话(Session)
四、切换身份(RunAs)/多线程身份传播
五、退出
而咱们必须的功能就是一、二、5。到目前为止咱们就可使用Shiro进行应用程序的安全控制了,可是仍是缺乏如对Web验证、Java方法验证等的一些简化实现。
示例源代码:https://github.com/zhangkaitao/shiro-example;可加群134755960探讨Spring/Shiro技术。