realm是桥梁,是连接securitymanager 和数据库的桥梁
它需要继承自AuthenticatingRealm,并且重写其中的方法doGetAuthenticationInfo
package cn.taotao.dao; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.realm.AuthenticatingRealm; public class UserRealm extends AuthenticatingRealm { @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { Object principal=authenticationToken.getPrincipal(); // 这一步是需要去数据库取出密码的 Object credentials=new String("123456"); String realmName=this.getClass().getSimpleName(); // 这里的密码,是去数据库中取,根据token传来的用户名,去数据库中取。 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName); return info; } }
测试程序
@Test void testRealm(){ String username="zhangsan"; String password = "123456"; // 模拟用户键盘输入 // 创建工厂,注意引入的包名,SecurityManager 是shiro的包 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 取得安全管理器实例 DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance(); Realm userRealm= new UserRealm(); securityManager.setRealm(userRealm); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); AuthenticationToken authenticationToken = new UsernamePasswordToken(username,password); subject.login(authenticationToken); System.out.println("认证是否realm,:"+subject.isAuthenticated()); }