【追寻源码的世界】为什么securityManager要先setAuthenticator()再setRealms()

本文深入探讨了Shiro权限框架中securityManager配置的顺序问题。若在初始化securityManager时,先设置realms再设置authenticator,将避免未配置realm的错误。文章详细分析了AuthenticatingSecurityManager类的实现,揭示了setRealms和setAuthenticator方法的调用顺序对程序认证的影响。

项目上发现如果在初始化securityManager的时候,只能先setAuthenticator(),再setRealms(),否则在程序认证的时候就会报错

java.lang.IllegalStateException: Configuration error:  No realms have been configured!  One or more realms must be present to execute an authentication attempt.

故而决定探究一下这是为什么。

这个过程中的核心类是AuthenticatingSecurityManager

我们先看一下AuthenticatingSecurityManager这个类的继承关系

接下来我们就开始调试。

当在执行securityManager.setRealms()的时候,它会先来到RealmSecurityManager类中的setRealms()方法。

在设置完this.realms = realms;之后,就会执行this.afterRealmsSet()方法,可以看到AuthenticatingSecurityManager中也实现了这个方法。

然后我们便在AuthenticatingSecurityManager中给this.authenticator设置了realms。到此securityManager.setRealms(realms)执行完成。接下来设置authenticator。

接下来就会跑到AuthenticatingSecurityManager中的setAuthenticator()方法

在这里我们就会发现这个报错的关键所在了。我们之前setRealms(realms)的时候给this.authenticator设置了。

但是当我们在setRealms()方法之后再调用setAuthenticator()方法的话,我们相当于把AuthenticatingSecurityManager中的this.authenticator覆盖了。所以导致最终this.authticator中的realms=null

所以在程序做验证的时候,会说我们没有设置realms。

以上便是本次的调查结果~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值