【Shiro】5.多个Realm的使用和实现
在Realm的使用中,可能使用多个Realm。比如,支持账号、密码登录;支持手机号验证码登录;支持微信登录等。
1. 创建多个自定义Realm
创建多个自定义的Realm,分别处理不同类型的认证和授权逻辑。
public class CustomRealm1 extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 实现Realm1的授权逻辑 } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 实现Realm1的认证逻辑 } } public class CustomRealm2 extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 实现Realm2的授权逻辑 } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 实现Realm2的认证逻辑 } }
2. 配置Shiro
在Shiro配置类中配置多个Realm,并指定认证策略。
1 @Configuration 2 public class ShiroConfig { 3 4 @Bean 5 public SecurityManager securityManager(CustomRealm1 customRealm1, CustomRealm2 customRealm2) { 6 DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); 7 List<Realm> realms = new ArrayList<>(); 8 realms.add(customRealm1); 9 realms.add(customRealm2); 10 securityManager.setRealms(realms); 11 12 // 设置认证策略,这里使用AtLeastOneSuccessfulStrategy,只要一个Realm验证成功即可 13 ModularityRealmAuthenticator authenticator = new ModularityRealmAuthenticator(); 14 authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy()); 15 securityManager.setAuthenticator(authenticator); 16 17 return securityManager; 18 } 19 20 @Bean 21 public CustomRealm1 customRealm1() { 22 return new CustomRealm1(); 23 } 24 25 @Bean 26 public CustomRealm2 customRealm2() { 27 return new CustomRealm2(); 28 } 29 }
在上述代码中,创建了两个自定义的Realm:CustomRealm1和CustomRealm2,并在Shiro配置类中配置了这两个Realm。通过设置SecurityManager的Realms属性,可以指定多个Realm来处理认证和授权操作。同时,还设置了认证策略为AtLeastOneSuccessfulStrategy,表示只要一个Realm验证成功即可认证通过。
认证策略包括3种:
认证方式 | 描述 |
AtLeastOneSuccessfulStrategy |
只要有一个Realm认证成功,那么认证将视为成功 |
FirstSuccessfulStrategy |
第一个Realm认证成功,整体认证将视为成功,且后续ReaLm被忽略 |
AllSuccessfulStrategy |
所有Realm成功,认证视为成功 |
有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。