shiro快速入门

什么是shiro (What is Apache Shiro?)

Apache Shiro is a powerful and flexible open-source security framework that cleanly handles authentication, authorization, enterprise session management and cryptography.

Apache Shiro 是一个强大而灵活的开源安全框架,可以干净地处理身份验证、授权、企业会话管理和加密

架构 (Architecture)

Shiro 的架构有 3 个主要概念:

**Subject:**简单的理解为shiro为当前用户创建的对象,当前用户可以是任何事物

SecurityManager: 是 Shiro 架构的核心,它充当一种“伞形”对象,用于协调其内部安全组件,这些组件共同构成了一个SecurityManager。

Realms: Realms充当Shiro和 应用程序安全数据( 就是存储数据的地方) 之间的“桥梁”或“连接器”。一般会自定义Realm,来实现认证,授权等操作。

详细架构图:

shiro快速入门_第1张图片

里面的介绍可以看 Apache Shiro Architecture | Apache Shiro 官网的解释

快速入门(Get Started with Apache Shiro)

环境:JDK 1.8+ and Maven 3.0.3+

下载官方代码并解压缩。

[Apache Download Mirrors](https://shiro.apache.org/download.html)

shiro快速入门_第2张图片

用ideal打开,并等待maven以来下载完成

shiro快速入门_第3张图片

打开quickstart.java 文件,接下来开始看里面的main函数

shiro快速入门_第4张图片

入门三部曲

1:获取 SecurityManager 工厂,此处使用 shiro.ini 配置文件初始化 SecurityManager

2: 得到 SecurityManager 实例 并绑定给 SecurityUtils

3: 获取当前用户 subject

拿到subject之后,就是想干嘛就干嘛,shiro叫破喉咙也没用


    public static void main(String[] args) {

      
        
        // 1. 获取 SecurityManager 工厂,此处使用 shiro.ini 配置文件初始化 SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        // 2. 得到 SecurityManager 实例 并绑定给 SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 3. 获取当前用户 subject
        Subject subject = SecurityUtils.getSubject();
		//拿到subject之后,就是想干嘛就干嘛,shiro叫破喉咙也没用 0.0
 		playShiro(subject);
        //all done - log out!
        subject.logout();

        System.exit(0);
    }
private static void playShiro(Subject subject) {

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = subject.getSession();
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        System.out.println();
        System.out.println("Retrieved the correct value! [" + value + "]");
    }

    // shiro基本所有的操作都需要通过subject来实现,下面是几个常用的API
    // Do some stuff with a Session (no need for a web or EJB container!!!)
    // 存一些数据在shiro的session,这里的session不是servlet的session,是shiro自己的。
    Session session = subject.getSession();
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }

    // let's login the current user so we can check against roles and permissions:
    // 常见认证方式
    if (!subject.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                    "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    log.info("User [" + subject.getPrincipal() + "] logged in successfully.");

    //test a role:
    if (subject.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    if (subject.isPermitted("lightsaber:wield")) {
        log.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        log.info("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    if (subject.isPermitted("winnebago:drive:eagle5")) {
        log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }
}

到这里shiro简单的认证就结束了。下一篇我将给大家来一个实战案例,关注我,期待下一篇

og.info(“Sorry, you aren’t allowed to drive the ‘eagle5’ winnebago!”);
}
}






到这里shiro简单的认证就结束了。下一篇我将给大家来一个实战案例,关注我,期待下一篇

















你可能感兴趣的:(安全框架,java,安全架构,后端)