• shiro-quick start


    1.1什么是Shiro

        1.Apache Shiro是一个java的安全(权限)框架

        2.JavaSE和JavaEE都可以使用

        3.shiro作用在认证,授权,加密,会话管理,Web集成,缓存等

        4.下载地址:https://shiro.apache.org

    2.shiro架构(外部)

      从应用程序角度来观察如何使用shiro完成工作:

        

     

    3.shiro架构(内部)

     

    4.quick start

      4.1导包

        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.7.0</version>
            </dependency>
    
    
            <!-- configure logging -->
            <!-- 日志门面-->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>1.7.26</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.26</version>
            </dependency>
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
        </dependencies>

    注意:slf4j和log4j的兼容版本去去maven仓库查看或者去shiro官网查看

      4.2静态资源配置文件和QuickStart类复制官网的即可

    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.*;
    
    import org.apache.shiro.config.IniSecurityManagerFactory;
    import org.apache.shiro.mgt.DefaultSecurityManager;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.realm.text.IniRealm;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.subject.Subject;
    
    import org.apache.shiro.util.Factory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    
    /**
     * Simple Quickstart application showing how to use Shiro's API.
     *
     * @since 0.9 RC2
     */
    public class Quickstart {
    
        private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
    
    
        public static void main(String[] args) {
    
            DefaultSecurityManager securityManager = new DefaultSecurityManager();
            IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
            securityManager.setRealm(iniRealm);
    
            SecurityUtils.setSecurityManager(securityManager);
    
            // get the currently executing user:
            //获取当前的用户对象suject
            Subject currentUser = SecurityUtils.getSubject();
    
            // Do some stuff with a Session (no need for a web or EJB container!!!)
            //通过当前用户拿到session
            Session session = currentUser.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 (!currentUser.isAuthenticated()) {
    
                //Token:令牌
                UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
                //设置记住我
                token.setRememberMe(true);
                try {
                    currentUser.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?  er ror?
                }
            }
    
            //say who they are:
            //print their identifying principal (in this case, a username):
            log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    
            //test a role:
            if (currentUser.hasRole("schwartz")) {
                log.info("May the Schwartz be with you!");
            } else {
                log.info("Hello, mere mortal.");
            }
    
            //粗粒度
            //test a typed permission (not instance-level)
            if (currentUser.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 (currentUser.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!");
            }
    
            //注销
            //all done - log out!
            currentUser.logout();
    
            //结束
            System.exit(0);
        }
    }

    5,subject相关的方法(从quickStart中得到)

    //获取当前的用户对象suject
    Subject currentUser = SecurityUtils.getSubject();
    
    //通过当前用户拿到session
    Session session = currentUser.getSession();
    
    //认证
    currentUser.isAuthenticated()
    
    //获取认证标识
    currentUser.getPrincipal()
    
    //授予当前用户角色
    currentUser.hasRole("schwartz")
    
    //获得当前用户的权限,根据给定的参数不同,获得的东西不同
    currentUser.isPermitted("winnebago:drive:eagle5")
    
    //注销
    //all done - log out!
    currentUser.logout();
    
    //结束
    System.exit(0);
  • 相关阅读:
    day7 面向对象 静态方法 类方法 属性方法 类的特殊成员方法 元类 反射 异常处理
    day6 面向对象 封装 继承 多态 类与实例在内存中的关系 经典类和新式类
    day5 time datetime random os sys shutil json pickle shelve xml configparser hashlib subprocess logging re正则 python计算器
    kafka常用操作命令
    linux基础
    django学习1——初识web应用程序
    mysql数据库(三)——pymysql模块
    mysql数据库(二)——表的查询
    mysql数据库(一)
    Python常用模块——re模块
  • 原文地址:https://www.cnblogs.com/CL-King/p/14158227.html
Copyright © 2020-2023  润新知