个人简介:Java领域新星创作者;阿里云技术博主、星级博主、专家博主;正在Java学习的路上摸爬滚打,记录学习的过程~
个人主页:.29.的博客
学习社区:进去逛一逛~
⑥【Shiro】Shiro中,如何使多个自定义Realm规则生效?
- 多个Realm实现原理
- Shiro配置类,使多个Realm生效
多个Realm实现原理
- 当应用程序配置多个 Realm 时,例如:用户名密码校验、手机号验证码校验等等。Shiro 的 ModularRealmAuthenticator 会使用内部的 AuthenticationStrategy 组件判断认证是成功还是失败。
- AuthenticationStrategy 是一个无状态的组件,它在身份验证尝试中被询问 4 次(这4 次交互所需的任何必要的状态将被作为方法参数):
-
- (1)在所有 Realm 被调用之前
- (2)在调用 Realm 的 getAuthenticationInfo 方法之前
- (3)在调用 Realm 的 getAuthenticationInfo 方法之后
- (4)在所有 Realm 被调用之后
- 认证策略的另外一项工作就是聚合所有 Realm 的结果信息封装至一个AuthenticationInfo 实例中,并将此信息返回,以此作为 Subject 的身份信息 。
Shiro中的三种认证策略
:
AtLeastOneSuccessfulStrategy
:只要有一个(或更多)的 Realm 验证成功,那么认证将视为成功FirstSuccessfulStrategy
:第一个 Realm 验证成功,整体认证将视为成功,且后续 Realm 将被忽略AllSuccessfulStrategy
:所有 Realm 成功,认证才视为成功
ModularRealmAuthenticator类 内置的认证策略默认实现是 AtLeastOneSuccessfulStrategy 方式 可以通过配置修改策略。
Shiro配置类,使多个Realm生效
/*** @author .29.* @create 2024-03-17 11:14*/
@Configuration
public class ShiroConfig {@Autowiredprivate MyRealm myRealm;//配置SecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(){//1. 创建DefaultWebSecurityManager对象(安全管理器)DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();//2. 创建认证对象ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();//3. 设置认证策略为AllSuccessfulStrategymodularRealmAuthenticator.setAuthenticationStrategy(new AllSuccessfulStrategy());//4. 将设置了认证策略的认证对象存入安全管理器defaultWebSecurityManager.setAuthenticator(modularRealmAuthenticator);//5. 封装Realm集合,存入多个自定义RealmArrayList<Realm> realms = new ArrayList<>();realms.add(myRealm1);realms.add(myRealm2);realms.add(myRealm3);//6.realm集合存入安全管理器defaultWebSecurityManager.setRealms(realms);//7.返回安全管理器return defaultWebSecurityManager; }}