• realme的shiro简单实现方法


    realm是桥梁,是连接securitymanager 和数据库的桥梁

    它需要继承自AuthenticatingRealm,并且重写其中的方法doGetAuthenticationInfo

    package cn.taotao.dao;
    
    
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.realm.AuthenticatingRealm;
    
    public class UserRealm extends AuthenticatingRealm {
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    
            Object principal=authenticationToken.getPrincipal();
            // 这一步是需要去数据库取出密码的
            Object credentials=new String("123456");
    
            String realmName=this.getClass().getSimpleName();
            // 这里的密码,是去数据库中取,根据token传来的用户名,去数据库中取。
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
            return info;
        }
    }

    测试程序

    @Test
        void testRealm(){
            String username="zhangsan";
            String  password = "123456";   // 模拟用户键盘输入
            // 创建工厂,注意引入的包名,SecurityManager 是shiro的包
            Factory<SecurityManager>  factory =  new IniSecurityManagerFactory("classpath:shiro.ini");
            // 取得安全管理器实例
            DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance();
            Realm userRealm= new UserRealm();
            securityManager.setRealm(userRealm);
    
            SecurityUtils.setSecurityManager(securityManager);
    
            Subject subject = SecurityUtils.getSubject();
            AuthenticationToken authenticationToken = new UsernamePasswordToken(username,password);
    
            subject.login(authenticationToken);
            System.out.println("认证是否realm,:"+subject.isAuthenticated());
    
    
        }
  • 相关阅读:
    POJ:1185-炮兵阵地(状压dp入门)
    LightOj:1422-Halloween Costumes
    HDU:4632-Palindrome subsequence
    POJ:2955-Brackets(经典:括号匹配)
    POJ:2342-Anniversary party(树形dp入门题目)
    HUD:2853-Assignment(KM算法+hash)
    HDU:2255-奔小康赚大钱(KM算法模板)
    POJ:3020-Antenna Placement(二分图的最小路径覆盖)
    POJ:3041-Asteroids(匈牙利算法模板)
    SVN
  • 原文地址:https://www.cnblogs.com/sdgtxuyong/p/15239292.html
Copyright © 2020-2023  润新知