Shiro 基础认证实现

//Shiro 认证基本实现流程

public class TestCustomerMD5 { public static void main(String[] args) {       //创建安全管理器对象 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
      //创建 自定义 realm CustomerMD5Realm realm = new CustomerMD5Realm(); //设置realm 使用hash凭证匹配器 HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); //使用算法 hashedCredentialsMatcher.setHashAlgorithmName("md5"); //散列次数 hashedCredentialsMatcher.setHashIterations(2048); realm.setCredentialsMatcher(hashedCredentialsMatcher); defaultSecurityManager.setRealm(realm); //将安全管理器注入安全工具 SecurityUtils.setSecurityManager(defaultSecurityManager); //通过安全工具类获取subject Subject subject = SecurityUtils.getSubject(); //认证 UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "48694869");
try { subject.login(token); System.out.println(subject.isAuthenticated()); System.out.println("登录成功"); } catch (AuthenticationException e) { e.printStackTrace(); } } }

 

public class CustomerMD5Realm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

  //调用login方法将进入该方法 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    //传递token对象,获取用户名 String principal = (String) authenticationToken.getPrincipal();       //模拟jdbc mybatis
if("xiaochen".equals(principal)){         //用户名正确进来,创建对象,切把查询到的username,password,salt,传递进去。 //参数1:数据库名字 参数2:数据库md5+salt之后的密码, 参数3:salt 参数4:realm名称 SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, "8b43662b349c05514580fd738e8ff382", ByteSource.Util.bytes("islove*021"), //如果有盐校验时默认加上 this.getName()); return simpleAuthenticationInfo;    //这里返回会去自动校验密码,这里的方法是查询name传递密码数据 } return null; } }

 

上一篇:多Realm验证策略


下一篇:android Realm 优化