使用Apache Shiro进行身份认证-多数据源认证

使用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 classDescription
AtLeastOneSuccessfulStrategyIf one (or more) Realms authenticate successfully, the overall attempt is considered successful. If none authenticate succesfully, the attempt fails.
FirstSuccessfulStrategyOnly 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.
AllSuccessfulStrategyAll 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实例对象中。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值