一、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的更多相关文章

  1. shiro学习笔记_0100_shiro简介

    前言:第一次知道shiro是2016年夏天,做项目时候我要写springmvc的拦截器,申哥看到后,说这个不安全,就给我捣鼓了shiro,我就看了下,从此认识了shiro.此笔记是根据网上的视频教程记 ...

  2. Apcahe Shiro学习笔记(二):通过JDBC进行权限控制

    一.概述: 官方对Realm(领域)的描述:https://www.infoq.com/articles/apache-shiro 其功能本质上是一个安全特定的DAO,用于链接数据持久层(任何形式的都 ...

  3. Linux内核学习笔记-1.简介和入门

    原创文章,转载请注明:Linux内核学习笔记-1.简介和入门 By Lucio.Yang 部分内容来自:Linux Kernel Development(Third Edition),Robert L ...

  4. shiro学习笔记_0600_自定义realm实现授权

    博客shiro学习笔记_0400_自定义Realm实现身份认证 介绍了认证,这里介绍授权. 1,仅仅通过配置文件来指定权限不够灵活且不方便.在实际的应用中大多数情况下都是将用户信息,角色信息,权限信息 ...

  5. Shiro学习笔记总结,附加" 身份认证 "源码案例(一)

    Shiro学习笔记总结 内容介绍: 一.Shiro介绍 二.subject认证主体 三.身份认证流程 四.Realm & JDBC reaml介绍 五.Shiro.ini配置介绍 六.源码案例 ...

  6. Shiro学习笔记(5)——web集成

    Web集成 shiro配置文件shiroini 界面 webxml最关键 Servlet 測试 基于 Basic 的拦截器身份验证 Web集成 大多数情况.web项目都会集成spring.shiro在 ...

  7. Shiro 学习笔记(一)——shiro简介

    Apache Shiro 是一个安全框架.说白了,就是进行一下 权限校验,判断下这个用户是否登录了,是否有权限去做这件事情. Shiro 可以帮助我们完成:认证.授权.加密.会话管理.与web 集成. ...

  8. React学习笔记 - JSX简介

    React Learn Note 2 React学习笔记(二) 标签(空格分隔): React JavaScript 一.JSX简介 像const element = <h1>Hello ...

  9. Android(java)学习笔记160:Framework运行环境之 Android进程产生过程

    1.前面Android(java)学习笔记159提到Dalvik虚拟机启动初始化过程,就下来就是启动zygote进程: zygote进程是所有APK应用进程的父进程:每当执行一个Android应用程序 ...

随机推荐

  1. ——CentOS 7 安装SQL Server2019

    环境准备  不废话,先把研究环境搭建起来.由于某些原因(晚点再说),本系列首先使用CentOS 7作为操作系统.官方指引中支持的Linux平台及文件系统中并没有指出CentOS,但是作为与Red Ha ...

  2. bzoj 1572: [Usaco2009 Open]工作安排Job

    Description Farmer John 有太多的工作要做啊!!!!!!!!为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间. 他的工作日从0时刻开始,有1000000000个单 ...

  3. WIFI万能钥匙协议分析

    WIFI万能钥匙协议分析 需求: 上android 市场下载任意一款,wifi万能钥匙 软件,对其进行 协议分析和逆向,达成如下结果:通过对软件的分析,完成自动化爬虫,爬wifi万能钥匙的wifi库, ...

  4. Github与Eclipse连接(方法2成功:Pleiades)

    2018-3-7 第1次尝试 主要参考这位大神的笔记:http://blog.csdn.net/zhangdaiscott/article/details/16939165 方法非常简单,从官网htt ...

  5. codeforces 446C DZY Loves Fibonacci Numbers 数论+线段树成段更新

    DZY Loves Fibonacci Numbers Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d &a ...

  6. Enable and Use Remote Commands in Windows PowerShell

    The Windows PowerShell remoting features are supported by the WS-Management protocol and the Windows ...

  7. es6总结(一)--let和const

    /*es6 是强制使用严格模式*/ /**/ function test(){ for(let i=0;i<10;i++){ console.log(i)//let生命的变量只在其声明的代码块中 ...

  8. Perl语言入门--4--列表

    1.列表也是数组的形式:(1,'a',2,3,4) 元素可以是任意类型,变量,表达式 2.空列表:() 单元素列表:(2)  .与值2不同 qw(1 $a str)   #qw是用空格作为分隔符,元素 ...

  9. LeetCode OJ--Median of Two Sorted Arrays ***

    http://oj.leetcode.com/problems/median-of-two-sorted-arrays/ 找两个有序数组的中位数,因为有序数组,并且复杂度要求O(lg(m+n))所以想 ...

  10. Cryptography I 学习笔记 --- 绪论

    课程地址 1. 密码学可以用于保证消息传递的机密性(第三方不可能得到明文)与完整性(密文如果被第三方篡改,有手段可以检测到) 2. 数字签名(用私钥加密待签名文件的hash值) 3. 匿名通信(mix ...