/** * 自定义的Realm * @author dengp * */ public class MyRealm extends AuthorizingRealm{ /** * 认证方法 * @param token * 就是我们在测试代码中 定义的UsernamePasswordToken对象 * 有我们保存的需要验证的账号密码信息 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 获取账号信息 String principal = (String) token.getPrincipal(); // 正常逻辑此处应该根据账号去数据库中查询,此处我们默认账号为 root 密码123456 // 验证账号 if(!"root".equals(principal)){ // 账号错误 return null; } String pwd = "123456"; // 验证密码 AuthenticationInfo info = new SimpleAuthenticationInfo(principal, pwd,"myrealm"); return info; } /** * 授权方法 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // TODO Auto-generated method stub return null; } }
[main] #自定义 realm customRealm=com.dpb.realm.MyRealm #将realm设置到securityManager securityManager.realms=$customRealm
@Test public void test() { // 1.获取SecurityManager工厂对象 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 2.通过Factory对象获取SecurityManager对象 SecurityManager securityManager = factory.getInstance(); // 3.将SecurityManager对象添加到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); // 4.获取Subject对象 Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("root1", "12345"); // 登录操作 try { subject.login(token); } catch (UnknownAccountException e) { System.out.println("账号出错..."); } catch(IncorrectCredentialsException e){ System.out.println("密码出错..."); } // 获取登录的状态 System.out.println(subject.isAuthenticated()); }