Shiro的使用及原理(一)

Shiro的使用及原理(一)

加密算法使用MD5不可逆加密

public static void main(String[] args) {
        //MD5加密
        Md5Hash md5Hash = new Md5Hash("666", "123", 64);
        System.out.println(md5Hash);
    }

自定义Realm实现数据库查询认证

public class PasswordRealm extends AuthorizingRealm {

    public String getName() {
        return "passwordRealm";
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //通过用户名查询数据库,进行认证
        //在token中拿到用户名
        String username = (String) authenticationToken.getPrincipal();
        //通过用户名查询数据库
        if (!"zhangsan".equals(username)) {
            return null;
        }
        //假设查询数据库
        String passsword = "664f16cf4ce56a454f348d3bfea194df";
        //info对象表示realm登录比对信息
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, passsword, ByteSource.Util.bytes("123"),getName());
        return info;
    }
}

编写测试代码测试登录

@Test
    public void testLogin() {
        //构建SecurityManager工程对象
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
        //通过工厂对象创建出SecurityManager对象
        SecurityManager securityManager = factory.getInstance();
        //绑定securityManager到当前运行系统中,让系统随时使用
        SecurityUtils.setSecurityManager(securityManager);
        //创建当前登录的主体,拿到此时的主体
        Subject subject = SecurityUtils.getSubject();
        //绑定主体登录的身份/凭证
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","666");
        //主体登录
        try {
            subject.login(token);
        } catch(Exception ex) {
            //登录异常
        }
        //判断登录成功
        System.out.println("验证登录成功与否" + subject.isAuthenticated());
        //登出
        subject.logout();
        System.out.println("验证登录成功与否" + subject.isAuthenticated());
    }
}

shiro在解密过程中帮我们做好了所有工作,我们只需要在配置文件中配置加密过程中使用的参数即可。同时希望提到shiro的subject,realm,securityManager这个3个核心,一切的操作api的底层都是由securityManager来实现的,所以都需要注入到securityManager中,相当于前端控制器

[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.credential.HashdeCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#将凭证匹配设置到realm
myRealm=shiro.PasswordRealm
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm

shiro是一款比较流行的框架,为我们做了很多事情,提高功能的实现效率,在此提供基础的学习代码,后续还会有shiro和spring等的集成以及实际使用!!!!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值