Apcahe Shiro学习笔记:简介及运行官方Demo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Apcahe Shiro学习笔记:简介及运行官方Demo相关的知识,希望对你有一定的参考价值。
一、Apache Shrio:
apache shiro 是一个功能强大和易于使用的Java安全框架,为开发人员提供一个直观而全面的的解决方案的认证,授权,加密,会话管理。
支持认证跨一个或多个数据源(LDAP,JDBC,kerberos身份等)
执行授权,基于角色的细粒度的权限控制。
增强的缓存的支持。
支持web或者非web环境,可以在任何单点登录(SSO)或集群分布式会话中使用。
主要功能是:认证,授权,会话管理和加密。
二、下载Shrio分发源码:
运行Demo需要使用Apache Maven,下载链接:http://maven.apache.org/download.cgi
Shrio 官方10分钟教程链接:http://shiro.apache.org/10-minute-tutorial.html
Shrio分发源码下载地址:http://shiro.apache.org/download.html#latestSource
点击zip进行下载
随意选择一个下载源
下载的压缩包的目录
三、运行Shiro Demo:
进入解压路径下的~\\samples\\quickstart,运行 mvn compile exec:java 命令
第一次运行将下载很多的依赖jar包,运行结果如下(红色框部分为程序的打印输出):
四、分析Shiro Demo:
首先我们先来查看下shiro的配置文件~\\samples\\quickstart\\src\\main\\resources\\shiro.ini。
# # ........Apache License 说明 # # ============================================================================= # Quickstart INI Realm configuration # # For those that might not understand the references in this file, the # definitions are all based on the classic Mel Brooks‘ film "Spaceballs". ;) # ============================================================================= # ----------------------------------------------------------------------------- # Users and their assigned roles # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc # ----------------------------------------------------------------------------- [users] # 创建一个角色‘root‘,设置密码为‘secret‘,添加角色‘admin‘ root = secret, admin # 创建一个角色‘guest‘,设置密码为‘guest‘,添加角色‘guest‘ guest = guest, guest # 创建一个角色‘presidentskroob ‘,设置密码为‘12345‘,添加角色‘president‘ presidentskroob = 12345, president # 创建一个角色‘darkhelmet ‘,设置密码为‘ludicrousspeed‘,添加角色‘darklord‘和‘schwartz‘ darkhelmet = ludicrousspeed, darklord, schwartz # 创建一个角色‘lonestarr‘,设置密码为‘vespa‘,添加角色‘goodguy‘和‘schwartz‘ lonestarr = vespa, goodguy, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc # ----------------------------------------------------------------------------- [roles] # 创建一个角色‘admin‘,通过通配符‘*‘表示拥有所有的权限 admin = * # 创建一个角色‘schwartz ‘,拥有‘lightsaber‘下的所有的权限 schwartz = lightsaber:* # The ‘goodguy‘ role is allowed to ‘drive‘ (action) the winnebago (type) with # license plate ‘eagle5‘ (instance specific id) goodguy = winnebago:drive:eagle5
查看java代码,~\\samples\\quickstart\\src\\main\\java\\Quickstart.java。
/* * Apache License 说明 */ 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; /** * 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) { // 通过IniSecurityManagerFactory载入ini文件,创建Factory Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 获取SecurityManager类 SecurityManager securityManager = factory.getInstance(); // SecurityUtils配置SecurityManager SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let‘s see what you can do: // 获取当前正在执行的用户 Subject currentUser = SecurityUtils.getSubject(); // 获取Shrio封装好的Session类(不是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 + "]"); } // 判断当前用户是否已经进行了认证 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? error? } } // 获取认证主体,由于之前使用的是UsernamePasswordToken,所有这里是获取的用户名 log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); // 测试角色 if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } // 测试权限 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!"); } // 登出 currentUser.logout(); System.exit(0); } }
再次对照一下cmd的打印输出。
转载请标明转载出处 : https://i.cnblogs.com/EditPosts.aspx?postid=7110166
以上是关于Apcahe Shiro学习笔记:简介及运行官方Demo的主要内容,如果未能解决你的问题,请参考以下文章