Shiro笔记(二)----shiro源码与默认提供的示例

来源:互联网 发布:数控车床螺纹编程 编辑:程序博客网 时间:2024/05/18 23:57

一、源码下载


Shiro官网地址为:http://shiro.apache.org/




点击Download进行下载页面




往下滑选择源码进行下载




下载下来之后解压结构如下




二、默认示例


在Sample目录下提供了一些示例




打开Eclipse选择导入Maven项目,导入之后如下




先来看下samples-quickstart提供的示例:


import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.*;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;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;/** * 简单的快速入门应用程序,显示如何使用Shiro的API。 * * @since 0.9 RC2 */public class Quickstart {    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);    public static void main(String[] args) {    //最简单的方法来创建配置好的Shiro SecurityManager    //领域、用户、角色和权限是使用简单的INI配置。    //我们将通过使用可以摄取.ini文件的工厂来执行此操作    //返回一个SecurityManager实例:    //在类路径的根目录下使用shiro.ini文件    //(file:和url:前缀分别从文件和网址加载):        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");        SecurityManager securityManager = factory.getInstance();    //为这个简单的例子快速启动,使安全管理器    //作为JVM单例访问。 大多数应用程序不会这样做    //而是依赖于他们的容器配置或web.xml    //webapps。 这是在这个简单的快速启动的范围之外,所以//我们只是做最少的最低限度,这样你就能继续得到感觉//做事情。        SecurityUtils.setSecurityManager(securityManager);        // 现在,设置了一个简单的Shiro环境,让我们看看你可以做什么:        // 获取当前正在执行的用户:        Subject currentUser = SecurityUtils.getSubject();        // 做一些会话的东西(不需要一个web或EJB容器!!!)        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 + "]");        }        // 让我们登录当前用户,以便我们检查角色和权限:        // 测试当前的用户是否已经被认证. 即是否已经登录.        //  调用 Subject 的 isAuthenticated()         if (!currentUser.isAuthenticated()) {                // 把用户名和密码封装为 UsernamePasswordToken 对象            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");            token.setRememberMe(true);            try {                        // 执行登录.                 currentUser.login(token);                            // 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.             } catch (UnknownAccountException uae) {                            log.info("没有用户名 " + token.getPrincipal());                            // 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。             } catch (IncorrectCredentialsException ice) {                            log.info("账号密码 " + token.getPrincipal() + " 是不正确的!");                             // 用户被锁定的异常 LockedAccountException            } catch (LockedAccountException lae) {                            log.info("账户的用户名 " + token.getPrincipal() + " 被锁定.  " +                        "请与管理员联系以解锁。");            }            // ... 在这里捕获更多的异常(可能是针对您的应用程序的自定义的?)            //所有认证时异常的父类.             catch (AuthenticationException ae) {                //意外情况? 错误?            }        }        //说他们是谁        //打印他们的识别主体(在这种情况下是一个用户名):        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");        //测试一个角色:        //测试是否有某一个角色. 调用 Subject 的 hasRole 方法.         if (currentUser.hasRole("schwartz")) {            log.info("May the Schwartz be with you!");        } else {            log.info("Hello, mere mortal.");        }        //测试类型权限(不是实例级)        //测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。         if (currentUser.isPermitted("lightsaber:weild")) {            log.info("You may use a lightsaber ring.  Use it wisely.");        } else {            log.info("Sorry, lightsaber rings are for schwartz masters only.");        }        //一个(非常强大的)实例级权限:        //测试用户是否具备某一个行为.         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!");        }        //全部完成-退出!        //执行退出. 调用 Subject 的 Logout() 方法.         currentUser.logout();        System.exit(0);    }}



.ini配置文件内容为:

[users]root = secret, adminguest = guest, guestpresidentskroob = 12345, presidentdarkhelmet = ludicrousspeed, darklord, schwartzlonestarr = vespa, goodguy, schwartz[roles]admin = *schwartz = lightsaber:*goodguy = winnebago:drive:eagle5


完整的为:


## Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements.  See the NOTICE file# distributed with this work for additional information# regarding copyright ownership.  The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License.  You may obtain a copy of the License at##     http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied.  See the License for the# specific language governing permissions and limitations# under the License.## =============================================================================# 快速启动INI域配置## 对于那些可能不理解该文件中的引用的人,请参考# 这些定义都是基于 Mel Brooks' film "Spaceballs". ;)# =============================================================================# -----------------------------------------------------------------------------# 用户及其分配的角色## 每一行都符合定义的格式# org.apache.shiro.realm.text.TextConfigurationRealm # setUserDefinitions JavaDoc# -----------------------------------------------------------------------------[users]# 用户'root'密码是'secret'角色是'admin'root = secret, admin# 用户'guest'密码是'guest'角色是'guest'guest = guest, guest# 用户'presidentskroob'密码是'12345' ("That's the same combination on# my luggage!!!")角色为'president'presidentskroob = 12345, president# 用户 'darkhelmet'密码是'ludicrousspeed' 角色为 'darklord' 和 'schwartz'darkhelmet = ludicrousspeed, darklord, schwartz# 用户 'lonestarr' 密码是 'vespa' 角色为'goodguy' 和 'schwartz'lonestarr = vespa, goodguy, schwartz# -----------------------------------------------------------------------------# 具有已分配权限的角色# # 每行符合定义的格式# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc# -----------------------------------------------------------------------------[roles]# 'admin' 角色具有所有权限,由通配符'*'admin = *#  属于'schwartz' 角色的可以做任何事情(*)与任何 lightsaber:schwartz = lightsaber:*# 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with# license plate 'eagle5' (instance specific id)goodguy = winnebago:drive:eagle5


右键以JAVA application运行输出如下:


Retrieved the correct value! [aValue]User [lonestarr] logged in successfully. May the Schwartz be with you!You may use a lightsaber ring.  Use it wisely.You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun! 


原创粉丝点击