项目上发现如果在初始化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。
以上便是本次的调查结果~