在com.dw.shiro.realms下创建SecondRealm 验证方式改为SHA1验证 1. SecondRealm代码如下:
public class SecondRealm extends AuthenticatingRealm{ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("Second Realm doGetAuthenticationInfo"); //1.把AuthenticationToken转换为UsernamePasswordToken UsernamePasswordToken upToken=(UsernamePasswordToken) token; //2.从UsernamePasswordToken中获取username String username=upToken.getUsername();//表单输入的 //3.调用数据库的方法,从数据库中查询username对应的记录 System.out.println("从数据库获取用户名所对应的用户信息"); //4.若用户不存在,则可以抛出UnknownAccountException异常 if("unknown".equals(username)) {//模拟 throw new UnknownAccountException("用户不存在"); } //5.根据用户信息的情况,决定是否抛出其他异常 if("monster".equals(username)) {//模拟 throw new LockedAccountException("用户被锁定"); } //6.根据用户情况构建AuthenticationInfo对象并返回 ,通常实现类为SimpleAuthenticationInfo //以下信息是从数据库获取的 /* * principal:认证的实体信息,可以是username,也可以是实体类对象 * credentials:数据库中获取的密码 * realmName:当前realm对象的name,调用父类的getName()方法即可 */ Object principal=username; Object credentials="fc1709d0a95a6be30bc5926fdb7f22f4"; String realmName=getName(); SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, credentials, realmName); return info; } public static void main(String[] args) { String hashAlgorithmName="SHA1"; Object credentials="123456"; Object salt=ByteSource.Util.bytes("user"); int hashIterations=1024; Object result=new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations); System.out.println(result); } }2. 代码写完后在applicationContext.xml文件添加信息
<bean id="secondRealm" class="com.dw.shiro.realms.SecondRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="SHA1"></property> <property name="hashIterations" value="1024"></property> </bean> </property> </bean>3. 此时有两个realm,要把这两个realm配置成一个认证器,在applicationContext.xml中添加如下
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator"> <property name="realms"> <list> <ref bean="jdbcRealm"/> <ref bean="secondRealm"/> </list> </property> </bean>4.修改securityManager
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="cacheManager" ref="cacheManager" /> <!-- <property name="realm" ref="jdbcRealm" /> --> <property name="authenticator" ref="authenticator" /> </bean>5.输入 user 123456 登录,控制台输出 说明两个Realm都可以使用了。 ShiroRealm先起作用,然后SecondRealm起作用。他们两个有先后顺序。 Shiro默认的认证策略是只要有一个Realm验证成功就可以了。
源码如下:
