使用Apache Shiro 可以非常容易地基于一个或多个数据源进行身份认证,使用多数据源时可以返回一个针对用户的联合视图。
可以通过使用认证策略来自定义一个认证流程,这些工作都是通过修改配置文件来完成的而无须修改代码。
这样可降低项目实施的复杂性和维护工作。
本例子中使用了两个数据源:数据库和LDAP。配置文件如下:
#首先定义两个数据源
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.serverName = 127.0.0.1
ds.user = root
ds.password = 123456
ds.databaseName = sample
ds.url = jdbc:mysql://127.0.0.1:3306/sample
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT CREDENCE_APPEND FROM user_credence_information WHERE CREDENCE_UNIQUEID = ?
ldapRealm = main.java.name.peter.shiro.realm.ldap.LdapAuthenticator
ldapRealm.rootDN = dc=example,dc=com
ldapRealm.contextFactory.url = ldap://localhost:389
ldapRealm.contextFactory.systemUsername = cn=Manager,dc=example,dc=com
ldapRealm.contextFactory.systemPassword = secret
#定义认证顺序
securityManager.realms = $jdbcRealm, $ldapRealm
#定义认证策略
authcStrategy = org.apache.shiro.authc.pam.AllSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy
Shiro本身定义了3种认证策略:
AuthenticationStrategy class | Description |
---|---|
AtLeastOneSuccessfulStrategy | If one (or more) Realms authenticate successfully, the overall attempt is considered successful. If none authenticate succesfully, the attempt fails. |
FirstSuccessfulStrategy | Only the information returned from the first successfully authenticated Realm will be used. All further Realms will be ignored. If none authenticate successfully, the attempt fails. |
AllSuccessfulStrategy | All configured Realms must authenticate successfully for the overall attempt to be considered successful. If any one does not authenticate successfully, the attempt fails. |
你也可以自己实现认证策略。通过扩展org.apache.shiro.authc.pam.AbstractAuthenticationStrategy来定义自己的认证策略。 AbstractAuthenticationStrategy 类会
自动将每个数据源的认证结果合并成一个 AuthenticationInfo实例对象中。