zoukankan      html  css  js  c++  java
  • 自定义Realm

    自定义Realm类

    在项目中新建com.bjsxt.realm.MyRealm

    public class MyRealm extends AuthenticatingRealm {
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            System.out.println("执行认证");
            //用户名
            String username = token.getPrincipal().toString();
            //密码
            String pwd = new String((char[])token.getCredentials());
            System.out.println(username+"  "+pwd);
            //先从数据库查询select * from user where username=? 查看用户名是否存在
            if(username.equals("admin")){//假设用户名为admin时能从数据库中查询出来
                //根据之前查询出来的用户信息获取密码。假设查询出来的密码是pwd
                String password= "pwd";
                //此处需要注意,第二个参数是从数据库查询出来的密码,而不是传递过来的密码。
                //第三个参数自定义。但是尽量不重复了。常直接使用用户名当做realname名字。
                AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(),password,"realmname");
                //shiro会判断从数据库查询出来的密码和客户端传递过来的密码是否一致。
                return info;
            }
            //返回null说明用户名不存在。
            return null;
        }
    }
    

      

    修改配置文件

    在配置文件中添加下面内容

    [main]
    myrealm=com.bjsxt.realm.MyRealm
    securityManager.realms=$myrealm
    

      

    测试结果

    ShiroRun中修改用户名和密码,当用户名和密码为admin、pwd时可以正常登录。

    此时无论shiro.ini是否配置了[users],都按照Realm中配置的逻辑进行比较用户名和密码。

    一、 凭证匹配器

    在实际应用中数据库密码都是加密的。Shiro内置了凭证匹配器,通过简单配置就可以实现明文数据和数据库中加密数据匹配的效果。

    修改自定义Realm

    AuthenticationInfo 的构造方法由三个参数变成四个参数的。新增第三个参数表示加盐。

    一般都是拿用户数据的id作为盐。

    //密码必须是MD5加密后的密码
    String password= "7614fd642608ca0755b78d2b2c352e19";
    //假设id是从数据库中取出的id
    Long id = 123L;
    //第三个参数是加密的盐
    AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), password, ByteSource.Util.bytes(id+"") ,token.getPrincipal().toString());
    

      

    修改配置文件

    在配置文件中配置凭证匹配器配置。

    [main]
    md5CredentialsMatcher=org.apache.shiro.authc.credential.Md5CredentialsMatcher
    md5CredentialsMatcher.hashIterations=2
    
    
    myrealm=com.bjsxt.shiro.MyRealm
    myrealm.credentialsMatcher=$md5CredentialsMatcher
    securityManager.realms=$myrealm
    

      

  • 相关阅读:
    菜单项向子页面传递参数
    Grid中添加链接,打开选项卡页面
    FineUI与百度地图简单示例 (转帖)
    AppBox中main树节点单击事件JS(还有叶子的节点的页面链接)
    FineUI中在一个页面中通过控件事件(JS)向父页面中添加Tab页
    如何使用button在tab中新建打开一个链接页
    系统service
    官员详解官场对领导称谓讲究:叫大不叫小
    搞笑对话
    陆琪:男人生存的意义,就是赚钱养老婆
  • 原文地址:https://www.cnblogs.com/vincentmax/p/14339642.html
Copyright © 2011-2022 走看看