shiro教程(2)- shiro介绍
shiro教程系列
shiro教程(3)-shiro授权
1 shiro介绍
1.1 什么是shiro
Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架。
1.2 为什么要学shiro
既然shiro将安全认证相关的功能抽取出来组成一个框架,使用shiro就可以非常快速的完成认证、授权等功能的开发,降低系统成本。
shiro使用广泛,shiro可以运行在web应用,非web应用,集群分布式应用中越来越多的用户开始使用shiro。
java领域中spring security(原名Acegi)也是一个开源的权限管理框架,但是spring security依赖spring运行,而shiro就相对独立,最主要是因为shiro使用简单、灵活,所以现在越来越多的用户选择shiro。
1.3 Shiro架构
1.3.1 Subject
Subject即主体,外部应用与subject进行交互,subject记录了当前操作用户,将用户的概念理解为当前操作的主体,可能是一个通过浏览器请求的用户,也可能是一个运行的程序。 Subject在shiro中是一个接口,接口中定义了很多认证授相关的方法,外部程序通过subject进行认证授,而subject是通过SecurityManager安全管理器进行认证授权
1.3.2 SecurityManager
SecurityManager即安全管理器,对全部的subject进行安全管理,它是shiro的核心,负责对所有的subject进行安全管理。通过SecurityManager可以完成subject的认证、授权等,实质上SecurityManager是通过Authenticator进行认证,通过Authorizer进行授权,通过SessionManager进行会话管理等。
SecurityManager是一个接口,继承了Authenticator, Authorizer, SessionManager这三个接口。
1.3.3 Authenticator
Authenticator即认证器,对用户身份进行认证,Authenticator是一个接口,shiro提供ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数需求,也可以自定义认证器。
1.3.4 Authorizer
Authorizer即授权器,用户通过认证器认证通过,在访问功能时需要通过授权器判断用户是否有此功能的操作权限。
1.3.5 realm
Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户权限数据,比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息。
注意:不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验的相关的代码。
1.3.6 sessionManager
sessionManager即会话管理,shiro框架定义了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web应用上,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录。
1.3.7 SessionDAO
SessionDAO即会话dao,是对session会话操作的一套接口,比如要将session存储到数据库,可以通过jdbc将会话存储到数据库。
1.3.8 CacheManager
CacheManager即缓存管理,将用户权限数据存储在缓存,这样可以提高性能。
1.3.9 Cryptography
Cryptography即密码管理,shiro提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。
1.4 shiro的jar包
与其它java开源框架类似,将shiro的jar包加入项目就可以使用shiro提供的功能了。shiro-core是核心包必须选用,还提供了与web整合的shiro-web、与spring整合的shiro-spring、与任务调度quartz整合的shiro-quartz等,下边是shiro各jar包的maven坐标。
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-quartz</artifactId><version>1.2.3</version></dependency>也可以通过引入shiro-all包括shiro所有的包:<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-all</artifactId><version>1.2.3</version></dependency>
参考lib目录 :
2 shiro认证
2.1 认证流程
2.2 入门程序(用户登陆和退出)
2.2.1 创建java工程
jdk版本:1.7.0_72
eclipse:elipse-indigo
2.2.2 加入shiro-core的Jar包及依赖包
2.2.3 log4j.properties日志配置文件
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
2.2.4 shiro.ini
通过Shiro.ini配置文件初始化SecurityManager环境。
配置 eclipse支持ini文件编辑:
在eclipse配置后,在classpath创建shiro.ini配置文件,为了方便测试将用户名和密码配置的shiro.ini配置文件中:
[users]
zhang=123
lisi=123
2.2.5 认证代码
// 用户登陆、用户退出@Testpublic void testLoginLogout() {// 构建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");// 通过工厂创建SecurityManagerSecurityManager securityManager = factory.getInstance();// 将securityManager设置到运行环境中SecurityUtils.setSecurityManager(securityManager);// 创建一个Subject实例,该实例认证要使用上边创建的securityManager进行Subject subject = SecurityUtils.getSubject();// 创建token令牌,记录用户认证的身份和凭证即账号和密码UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");try {// 用户登陆subject.login(token);} catch (AuthenticationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 用户认证状态Boolean isAuthenticated = subject.isAuthenticated();System.out.println("用户认证状态:" + isAuthenticated);// 用户退出subject.logout();isAuthenticated = subject.isAuthenticated();System.out.println("用户认证状态:" + isAuthenticated);}
2.2.6 认证执行流程
1、 创建token令牌,token中有用户提交的认证信息即账号和密码
2、 执行subject.login(token),最终由securityManager通过Authenticator进行认证
3、 Authenticator的实现ModularRealmAuthenticator调用realm从ini配置文件取用户真实的账号和密码,这里使用的是IniRealm(shiro自带)
4、 IniRealm先根据token中的账号去ini中找该账号,如果找不到则给ModularRealmAuthenticator返回null,如果找到则匹配密码,匹配密码成功则认证通过。
2.2.7 常见的异常
UnknownAccountException
账号不存在异常如下:
org.apache.shiro.authc.UnknownAccountException: No account found for user。。。。
IncorrectCredentialsException
当输入密码错误会抛此异常,如下:
org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - zhangsan, rememberMe=false] did not match the expected credentials.
更多如下:
DisabledAccountException(帐号被禁用)
LockedAccountException(帐号被锁定)
ExcessiveAttemptsException(登录失败次数过多)
ExpiredCredentialsException(凭证过期)等
2.3 自定义Realm
上边的程序使用的是Shiro自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm。
2.3.1 shiro提供的realm
最基础的是Realm接口,CachingRealm负责缓存处理,AuthenticationRealm负责认证,AuthorizingRealm负责授权,通常自定义的realm继承AuthorizingRealm。
2.3.2 自定义Realm
public class CustomRealm1 extends AuthorizingRealm {@Overridepublic String getName() {return "customRealm1";}//支持UsernamePasswordToken@Overridepublic boolean supports(AuthenticationToken token) {return token instanceof UsernamePasswordToken;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//从token中 获取用户身份信息String username = (String) token.getPrincipal();//拿username从数据库中查询//....//如果查询不到则返回nullif(!username.equals("zhang")){//这里模拟查询不到return null;}//获取从数据库查询出来的用户密码String password = "123";//这里使用静态数据模拟。。//返回认证信息由父类AuthenticatingRealm进行认证SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());return simpleAuthenticationInfo;}//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {// TODO Auto-generated method stubreturn null;}}
2.3.3 shiro-realm.ini
[main]#自定义 realmcustomRealm=com.sihai.shiro.authentication.realm.CustomRealm1#将realm设置到securityManagersecurityManager.realms=$customRealm
2.3.4 测试代码
测试代码同入门程序,将ini的地址修改为shiro-realm.ini。
分别模拟账号不存在、密码错误、账号和密码正确进行测试。
2.4 散列算法
散列算法一般用于生成一段文本的摘要信息,散列算法不可逆,将内容可以生成摘要,无法将摘要转成原始内容。散列算法常用于对密码进行散列,常用的散列算法有MD5、SHA。
一般散列算法需要提供一个salt(盐)与原始内容生成摘要信息,这样做的目的是为了安全性,比如:111111的md5值是:96e79218965eb72c92a549dd5a330112,拿着“96e79218965eb72c92a549dd5a330112”去md5破解网站很容易进行破解,如果要是对111111和salt(盐,一个随机数)进行散列,这样虽然密码都是111111加不同的盐会生成不同的散列值。
2.4.1 例子
//md5加密,不加盐String password_md5 = new Md5Hash("111111").toString();System.out.println("md5加密,不加盐="+password_md5);//md5加密,加盐,一次散列String password_md5_sale_1 = new Md5Hash("111111", "eteokues", 1).toString();System.out.println("password_md5_sale_1="+password_md5_sale_1);String password_md5_sale_2 = new Md5Hash("111111", "uiwueylm", 1).toString();System.out.println("password_md5_sale_2="+password_md5_sale_2);//两次散列相当于md5(md5())//使用SimpleHashString simpleHash = new SimpleHash("MD5", "111111", "eteokues",1).toString();System.out.println(simpleHash);
2.4.2 在realm中使用
实际应用是将盐和散列后的值存在数据库中,自动realm从数据库取出盐和加密后的值由shiro完成密码校验。
2.4.2.1 自定义realm
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//用户账号String username = (String) token.getPrincipal();//根据用户账号从数据库取出盐和加密后的值//..这里使用静态数据//如果根据账号没有找到用户信息则返回null,shiro抛出异常“账号不存在”//按照固定规则加密码结果 ,此密码 要在数据库存储,原始密码 是111111,盐是eteokuesString password = "cb571f7bd7a6f73ab004a70322b963d5";//盐,随机数,此随机数也在数据库存储String salt = "eteokues";//返回认证信息SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt),getName());return simpleAuthenticationInfo;}
2.4.2.2 realm配置
配置shiro-cryptography.ini
[main]#定义凭证匹配器credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher#散列算法credentialsMatcher.hashAlgorithmName=md5#散列次数credentialsMatcher.hashIterations=1#将凭证匹配器设置到realmcustomRealm=com.sihai.shiro.authentication.realm.CustomRealm2customRealm.credentialsMatcher=$credentialsMatchersecurityManager.realms=$customRealm
2.4.2.3 测试代码
测试代码同上个章节,注意修改ini路径。
shiro教程(2)- shiro介绍相关推荐
- Shiro 教程,Shiro教程0.2 下载,Shiro功能修复与升级说明。
2019独角兽企业重金招聘Python工程师标准>>> Shiro + SSM(框架) + Freemarker(jsp)讲解的权限控制Demo,还不赶快去下载? 原文链接:http ...
- Shiro教程_2 Shiro+SpringBoot+Mysql+Redis(缓存)
源代码 https://gitee.com/fakerlove/Shiro Shiro+SpringBoot+Mysql+Redis(缓存) 1. 添加依赖 <?xml version=&quo ...
- [Shiro教程] Shiro 教程基于SSM(SpringMVC + Spring + Mybatis)EHCache版本
一.Shiro简介 Apache Shiro 是 Java 的一个安全框架.我们经常看到它被拿来和 Spring 的 Security 来对比.大部分人认为 Shiro 比 Security ...
- [Shiro教程] Shiro 教程基于SSM(SpringMVC + Spring + Mybatis)
一.Shiro简介 Apache Shiro 是 Java 的一个安全框架.我们经常看到它被拿来和 Spring 的 Security 来对比.大部分人认为 Shiro 比 Security ...
- Shiro 教程_1
教案 https://gitee.com/fakerlove/Shiro 文章目录 Shiro 教程 1. Shiro 介绍 1.1 什么是 Shiro 1.2 Shiro 好处 1.3 Shiro ...
- 2017.2.16 开涛shiro教程-第十七章-OAuth2集成(一)服务器端
原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 开涛shiro教程-第十七章-OAuth2集成 1.OAuth2介 ...
- shiro教程1(HelloWorld)
shiro简介 官网 Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理.使用Shiro的易于理解的API,您可以快速.轻松地获得任何应用程序,从最小的 ...
- Apache Shiro教程
跟开涛学系列: 来自开涛的Apache Shiro教程:http://jinnianshilongnian.iteye.com/blog/2018398 附带的代码例子:https://github. ...
- Shiro教程,整合SpringBoot项目实战(笔记)
1.shiro 1.1什么是权限管理 基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己 ...
最新文章
- weblogic公布的项目用途myeclipse正常启动,点击startWeblogic.cmd报错解决方案
- 通过调整Linux内核参数提升网络性能
- php round函数输出不对_PHP常量
- P4083-[USACO17DEC]A Pie for a Pie G【线段树,最短路】
- Python 读写CSV文件
- PHP 查找链表倒数第i个节点
- [Python] L1-030. 一帮一-PAT团体程序设计天梯赛GPLT
- 大数据学习总结(5)参考elk技术架构
- sodp软件如何导入多个工作面信息_6款堪称业界良心的软件,好用到想为它们疯狂打call!...
- java计算机毕业设计风情旅游网站源码+mysql数据库+系统+lw文档+部署
- LabVIEW的VISA函数串口数据采集例子——温度采集系统
- android 5.1 改mac地址,mac地址可以随便改吗
- TLS完美前向保密(perfect forward secrecy)翻译
- checkpoints are occurring too frequently
- 在Windows下安装BIND作为DNS服务器
- USB 协议分析之 HID 设备
- 【计算机网络】TCP为什么需要4次挥手
- 【java】调用百度开发平台ai接口,完成人脸识别(人脸搜索、人脸对比、人脸检测等)功能--------超详细,适合小白
- ADI Blackfin DSP处理器-BF533的开发详解24:触摸屏的实现和应用(含源代码)
- Carthage入门篇-安装和使用