美文网首页
Shiro6-自定义 Realm 进行验证

Shiro6-自定义 Realm 进行验证

作者: 我相信你爱过gg | 来源:发表于2017-05-19 00:07 被阅读36次

在上一篇笔记中我们说过

IniRealm: 读取 ini 配置文件, 将来要连接数据,那么就需要仿照此类来读取数据库的账号和密码.

那么我们现在就要自定义一个 Realm 来从数据库中查询我们的用户信息.
注意: 我们一般自定义 Realm 实现都会实现 AuthorizingRealm 类.

自定义 Realm


    // 设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    // 用于认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {

        // token是用户输入的
        // 第一步从token中取出身份信息
        String userCode = (String) token.getPrincipal();

        // 第二步:根据用户输入的userCode从数据库查询
        // ....
    

        // 如果查询不到返回null
        //数据库中用户账号是zhangsansan
        /*if(!userCode.equals("zhangsansan")){//
            return null;
        }*/
        
        
        // 模拟从数据库查询到密码
        String password = "111112";

        // 如果查询到返回认证信息AuthenticationInfo

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userCode, password, this.getName());

        return simpleAuthenticationInfo;

配置 Realm

我们自定义的 Realm 需要注入到 SecurityManager 中,由于我们是通过 ini 文件配置的,所以我们要创建一个 shiro-realm.ini 来专门配置我们的 Realm.

[main]
#自定义 realm
customRealm= 报名+类名
#将 realm 设置到 SecurityManager 中.
securityManager.realms=$customRealm

securityManager.realms是固定的.
customRealm 是自定义的名字.

测试

Factory<SecurityManager> factory = new IniSecurityManagerFactory(
                "classpath:shiro-realm.ini");

只需要改这一句代码就可以了.

有人可能会问为什么不需要配置[users]了呢?
答:因为我们现在是模拟从数据库查询,而不是读取 ini 配置文件中的用户名密码了.

相关文章

网友评论

      本文标题:Shiro6-自定义 Realm 进行验证

      本文链接:https://www.haomeiwen.com/subject/dteexxtx.html