一、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. git统计日期之间的代码改动行数

    git log --pretty=tformat: --since ==2016-10-25 --until=2016-10-27   --numstat | awk '{ add += $1 ; s ...

  2. [LeetCode] Sort Colors 只有3个类型的排序

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  3. Java程序员最常犯的错误盘点之Top 10

    1. 数组转ArrayList 为了实现把一个数组转换成一个ArrayList,很多Java程序员会使用如下的代码: Arrays.asList确实会返回一个ArrayList对象,但是该类是Arra ...

  4. Atcoder CODE FESTIVAL 2017 qual B E - Popping Balls 组合计数

    题目链接 题意 \(A+B\)个球排成一行,左边\(A\)个为红球,右边\(B\)个为蓝球. 最开始可以选择两个数\(s,t\),每次操作可以取左起第\(1\)或\(s\)或\(t\)个球.问有多少种 ...

  5. How to debug Android Native Application with eclipse

    This blog is inspired by this tutorial http://mhandroid.wordpress.com/2011/01/23/using-eclipse-for-a ...

  6. FNV与FNV-1a Hash算法说明【转】

    转自:http://blog.csdn.net/jiayanhui2877/article/details/12090575 The core of the FNV hash The core of ...

  7. 标准C程序设计七---70

    Linux应用             编程深入            语言编程 标准C程序设计七---经典C11程序设计    以下内容为阅读:    <标准C程序设计>(第7版) 作者 ...

  8. U3D层的运用

    在操作 LayerMask 时常令一些初学者摸不着头脑下面简单说一下层的开关方法:1.首先引入'|'.'&'.'~'的概念与(交集):10000001 & 10000100 == 10 ...

  9. Vijos 1323: 化工厂装箱员

    题形:DP 题意:A,B,C三种物品,一共N个,顺序摆放,按顺序拿.每次手上最多能拿10个物品,然后可以将某个类别的物品分类放好,再从剩下的拿,补全10个.问最少放几次,可以把所有物品分类好. 思路: ...

  10. css-通过css让块显示或隐藏

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...