《跟我学Shiro》笔记06-Realm及相关对象
原文地址:第六章 Realm及相关对象——《跟我学Shiro》
目录贴: 跟我学Shiro目录贴
源码:https://github.com/zhangkaitao/shiro-example
Realm
public class UserRealm extends AuthorizingRealm {
private UserService userService = new UserServiceImpl();
@Override
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;
}
@Override
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;
}
}
UserRealm父类AuthorizingRealm将获取Subject相关信息分成两步:获取身份验证信息(doGetAuthenticationInfo)及授权信息(doGetAuthorizationInfo);doGetAuthenticationInfo获取身份验证相关信息:首先根据传入的用户名获取 User 信息;然后如果 user 为空,那么抛出没找到帐号异常UnknownAccountException;如果 user 找到但锁定了抛出锁定异常LockedAccountException;最后生成AuthenticationInfo信息,交给间接父类AuthenticatingRealm使用CredentialsMatcher进行判断密码是否匹配,如果不匹配将抛出密码错误异常IncorrectCredentialsException;另外如果密码重试此处太多将抛出超出重试次数异常ExcessiveAttemptsException;在组装SimpleAuthenticationInfo信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt),CredentialsMatcher使用盐加密传入的明文密码和此处的密文密码进行匹配。doGetAuthorizationInfo获取授权信息:PrincipalCollection是一个身份集合,因为我们现在就一个Realm,所以直接调用getPrimaryPrincipal得到之前传入的用户名即可;然后根据用户名调用UserService接口获取角色及权限信息。
AuthenticationToken

AuthenticationToken 用于收集用户提交的身份(如用户名)及凭据(如密码):
public interface AuthenticationToken extends Serializable {
Object getPrincipal(); //身份
Object getCredentials(); //凭据
}
扩展接口 RememberMeAuthenticationToken:提供了 boolean isRememberMe() 现“记住我”的功能;
扩展接口是 HostAuthenticationToken:提供了 String getHost() 方法用于获取用户“主机”的功能。
Shiro 提供了一个直接拿来用的 UsernamePasswordToken,用于实现用户名/密码 Token 组,另外其实现了 RememberMeAuthenticationToken 和 HostAuthenticationToken,可以实现记住我及主机验证的支持。
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 即可。
PrincipalCollection

因为我们可以在 Shiro 中同时配置多个 Realm,所以呢身份信息可能就有多个;因此其提供了 PrincipalCollection 用于聚合这些身份信息:
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
MutablePrincipalCollection 是一个可变的 PrincipalCollection 接口,即提供了如下可变方法:
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。
@Test
public void test() {
// 因为 Realm 里没有进行验证,所以相当于每个 Realm 都身份验证成功了
login("classpath:shiro-multirealm.ini", "zhang", "123");
Subject subject = SecurityUtils.getSubject();
// 获取 Primary Principal(即所谓的第一个)
Object primaryPrincipal1 = subject.getPrincipal();
PrincipalCollection princialCollection = subject.getPrincipals();
Object primaryPrincipal2 = princialCollection.getPrimaryPrincipal();
// 但是因为多个 Realm 都返回了 Principal,所以此处到底是哪个是不确定的,这里应该是相同
Assert.assertEquals(primaryPrincipal1, primaryPrincipal2);
// 获取所有身份验证成功的 Realm 名字,返回 a b c
Set<String> realmNames = princialCollection.getRealmNames();
System.out.println(realmNames);
// 因为 MyRealm1 和 MyRealm2 返回的凭据都是 zhang,所以排重了
Set<Object> principals = princialCollection.asSet(); // asList 和 asSet 的结果一样
System.out.println(principals);
// 根据 Realm 名字获取
Collection<User> users = princialCollection.fromRealm("c");
System.out.println(users);
// 因为 Realm 名字可以重复,所以可能多个身份,建议 Realm 名字尽量不要重复
}
AuthorizationInfo

AuthorizationInfo 用于聚合授权信息的:
public interface AuthorizationInfo extends Serializable {
Collection<String> getRoles(); // 获取角色字符串信息
Collection<String> getStringPermissions(); // 获取权限字符串信息
Collection<Permission> getObjectPermissions(); // 获取 Permission 对象信息
}
当我们使用 AuthorizingRealm 时,如果身份验证成功,在进行授权时就通过 doGetAuthorizationInfo 方法获取角色/权限信息用于授权验证。
Shiro 提供了一个实现 SimpleAuthorizationInfo,大多数时候使用这个即可。
对于 Account 及 SimpleAccount,之前的 AuthenticationInfo 已经介绍过了,用于 SimpleAccountRealm 子类,实现动态角色/权限维护的。
Subject

Subject 是 Shiro 的核心对象,基本所有身份验证、授权都是通过 Subject 完成。
Subject 自己不会实现相应的身份验证/授权逻辑,而是通过 DelegatingSubject 委托给 SecurityManager 实现;及可以理解为 Subject 是一个面门。
对于 Subject 的构建一般没必要我们去创建;一般通过 SecurityUtils.getSubject() 获取:
public static Subject getSubject() {
Subject subject = ThreadContext.getSubject();
if (subject == null) {
subject = (new Subject.Builder()).buildSubject();
ThreadContext.bind(subject);
}
return subject;
}
// 即首先查看当前线程是否绑定了 Subject,如果没有通过 Subject.Builder 构建一个然后绑定到现场返回。
如果想自定义创建,可以通过:
new Subject.Builder().principals(身份).authenticated(true/false).buildSubject()
这种可以创建相应的 Subject 实例了,然后自己绑定到线程即可。在 new Builder() 时如果没有传入 SecurityManager,自动调用 SecurityUtils.getSecurityManager 获取;也可以自己传入一个实例。
身份信息获取
Object getPrincipal(); // Primary Principal
PrincipalCollection getPrincipals(); // PrincipalCollection
身份验证
void login(AuthenticationToken token) throws AuthenticationException;
boolean isAuthenticated(); // 登录成功,返回 true
boolean isRemembered(); // 通过记住我功能登录,返回 true
通过 login 登录,如果登录失败将抛出相应的 AuthenticationException,如果登录成功调用 isAuthenticated 就会返回 true,即已经通过身份验证;如果 isRemembered 返回 true,表示是通过记住我功能登录的而不是调用 login 方法登录的。isAuthenticated/isRemembered 是互斥的,即如果其中一个返回 true,另一个返回 false。
角色授权验证
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 异常。
权限授权验证
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。
会话
ession getSession(); // 相当于 getSession(true)
Session getSession(boolean create);
类似于 Web 中的会话。如果登录成功就相当于建立了会话,接着可以使用 getSession 获取;如果 create=false 如果没有会话将返回 null,而 create=true 如果没有会话会强制创建一个。
退出
void logout();
RunAs
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即可。
多线程
<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 实例) 得到一个包装后的实例;它们都是通过:1、把当前线程的 Subject 绑定过去;2、在线程执行结束后自动释放。
一般使用
- 身份验证(login)
- 授权(
hasRole*/isPermitted*或checkRole*/checkPermission*) - 将相应的数据存储到会话(Session)
- 切换身份(RunAs)/多线程身份传播
- 退出
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com
文章标题:《跟我学Shiro》笔记06-Realm及相关对象
文章字数:2.5k
本文作者:Bin
发布时间:2018-04-13, 20:12:22
最后更新:2019-08-30, 16:30:00
原始链接:http://coolview.github.io/2018/04/13/%E8%B7%9F%E6%88%91%E5%AD%A6Shiro/%E3%80%8A%E8%B7%9F%E6%88%91%E5%AD%A6Shiro%E3%80%8B%E7%AC%94%E8%AE%B006-Realm%E5%8F%8A%E7%9B%B8%E5%85%B3%E5%AF%B9%E8%B1%A1/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。