Shiro安全框架03:自定义realm认证

第一步:在ini文件中配置

myRealm= com.ctbu.MyRealm
securityManager.realms=$myRealm

第二步:编写自定义realm

public class MyRealm extends AuthorizingRealm {

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //判断当前用户是否存在
        //获取用户名
        String username = (String)token.getPrincipal();
        //从数据库中取出用户名和密码
        String name ="hello";
        String password = "1234";

        //判断用户名是否相等
        if (!name.equals(username)){
            return null;
        }

        //这里的this.getName()获得的是类的名字
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, this.getName());
        return info;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}

第三步:运行认证

public static void main(String[] args) {
        /**
         * 1.构建securityManager工厂
         * 2.通过工厂创建securityManager
         * 3.将securityManager设置到运行环境中
         * 4.创建一个Subject实例
         * 5.创建token令牌
         * 6.用户登录
         * 7.用户退出
         */
        // 1.构建securityManager工厂
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //2.通过工厂创建securityManager
        SecurityManager securityManager = factory.getInstance();
        //3.将securityManager设置到运行环境中
        SecurityUtils.setSecurityManager(securityManager);
        //4.创建一个Subject实例
        Subject subject = SecurityUtils.getSubject();
        //5.创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("hello", "1234");


        try {
            //6.用户登录
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
        } catch (IncorrectCredentialsException e){
            System.out.println("密码不正确");
        }


        System.out.println("认证是否成功"+subject.isAuthenticated());
        //7.用户退出
        subject.logout();
        System.out.println("认证是否成功"+subject.isAuthenticated());
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值