shiro 入门,认证
2016-06-26 23:33
344 查看
1.1 什么是shiro
shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证、用户授权。spring中有spring security (原名Acegi),是一个权限框架,它和spring依赖过于紧密,没有shiro使用简单。
shiro不依赖于spring,shiro不仅可以实现
web应用的权限管理,还可以实现c/s系统,分布式系统权限管理,shiro属于轻量框架,越来越多企业项目开始使用shiro。
使用shiro实现系统 的权限管理,有效提高开发效率,从而降低开发成本。
subject:主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证、授权。
securityManager:安全管理器,主体进行认证和授权都 是通过securityManager进行。
authenticator:认证器,主体进行认证最终通过authenticator进行的。
authorizer:授权器,主体进行授权最终通过authorizer进行的。
sessionManager:web应用中一般是用web容器对session进行管理,shiro也提供一套session管理的方式。
SessionDao: 通过SessionDao管理session数据,针对个性化的session数据存储需要使用sessionDao。
cache Manager:缓存管理器,主要对session和授权数据进行缓存,比如将授权数据通过cacheManager进行缓存管理,和ehcache整合对缓存数据进行管理。
realm:域,领域,相当于数据源,通过realm存取认证、授权相关数据。
注意:在realm中存储授权和认证的逻辑。
cryptography:密码管理,提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。
比如 md5散列算法。
1.2 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>
2 shiro认证
2.1 shiro认证流程
2.2 shiro入门程序工程 环境
jar包:shiro-core.jar工程结构:
‘
工程结构:
2.3 shiro认证入门程序
2.3.1 shiro-first.ini
#对用户信息进行配置 [users] #用户名和密码 zhangsan=111111 lisi=22222
通过此配置文件创建securityManager工厂。
2.3.2 入门程序代码
package com.me.shiro.authentication; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.junit.Test; /* * 认证测试 */ public class AuthenticationTest { //用户登陆和退出 @Test public void testLoginAndLogout(){ //创建securityManager工厂,通过ini配置文件创建securityManager工厂 Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-first.ini"); //创建SecurityManager org.apache.shiro.mgt.SecurityManager securityManager= factory.getInstance(); //将secrityManager设置当前的运行环境中 SecurityUtils.setSecurityManager(securityManager); //从SecurityUtils里创建一个subject Subject subject = SecurityUtils.getSubject(); //在认证提交前准备token(令牌) //这里的帐号和密码 将来是由用户输入进去 UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111"); try { //执行认证提交 subject.login(token); } catch (Exception e) { e.printStackTrace(); } //是否认证通过 boolean isAuth = subject.isAuthenticated(); System.out.println("是否认证通过:"+isAuth); //退出操作 subject.logout(); //是否认证通过 isAuth = subject.isAuthenticated(); System.out.println("是否认证通过:"+isAuth); } } }
2.3.3 执行流程
1、通过ini配置文件创建securityManager
2、调用subject.login方法主体提交认证,提交的token
3、securityManager进行认证,securityManager最终由ModularRealmAuthenticator进行认证。
4、ModularRealmAuthenticator调用IniRealm(给realm传入token)
去ini配置文件中查询用户信息
5、IniRealm根据输入的token(UsernamePasswordToken)从
shiro-first.ini查询用户信息,根据账号查询用户信息(账号和密码)
如果查询到用户信息,就给ModularRealmAuthenticator返回用户信息(账号和密码)
如果查询不到,就给ModularRealmAuthenticator返回null
6、ModularRealmAuthenticator接收IniRealm返回Authentication认证信息
如果返回的认证信息是null,ModularRealmAuthenticator抛出异常(org.apache.shiro.authc.UnknownAccountException)
如果返回的认证信息不是null(说明inirealm找到了用户),对IniRealm返回用户密码 (在ini文件中存在)和
token中的密码 进行对比,如果不一致抛出异常(org.apache.shiro.authc.IncorrectCredentialsException)
2.3.4 小结:
ModularRealmAuthenticator作用进行认证,需要调用realm查询用户信息(在数据库中存在用户信息)ModularRealmAuthenticator进行密码对比(认证过程)。
realm:需要根据token中的身份信息去查询数据库(入门程序使用ini配置文件),如果查到用户返回认证信息,如果查询不到返回null。
3 自定义realm
将来实际开发需要realm从数据库中查询用户信息。3.1.1 realm接口
3.1.2 自定义realm
<span style="font-size: 16pt;">p</span><span style="font-size:14px;">ackage com.me.shiro.realm; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; /** * 自定义realm * @author Administrator * */ public class CustomRealm extends AuthorizingRealm{ @Override public void setName(String name) { // TODO Auto-generated method stub super.setName("customRealm"); } //用于认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //token是用户输入的 //第一步从token中取出身份信息 String userCode = (String) token.getPrincipal(); //第二步:根据用户输入的userCode从数据库查询 //... //如果查询不到返回null //数据库中用户帐号是zhangsan if(!"zhangsan".equals(userCode)){ return null; } //模拟从数据库查询到密码 String password = "111111"; //如果查询到返回认证信息AuthenticationInfo SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userCode, password, this.getName()); return authenticationInfo; } //用于授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { // TODO Auto-generated method stub return null; } }</span><span style="font-size: 16pt;"> </span>
3.1.3 配置realm
需要在shiro-realm.ini配置realm注入到securityManager中。[main]
#自定义 realm
customRealm=com.me.shiro.realm.CustomRealm
#将realm设置到securityManager,相当 于spring中注入
securityManager.realms=$customRealm
3.1.4 测试
/** * 自定义realm */ @Test public void testCustomRealm(){ //创建securityManager工厂,通过ini配置文件创建securityManager工厂 Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini"); //创建SecurityManager org.apache.shiro.mgt.SecurityManager securityManager= factory.getInstance(); //将secrityManager设置当前的运行环境中 SecurityUtils.setSecurityManager(securityManager); //从SecurityUtils里创建一个subject Subject subject = SecurityUtils.getSubject(); //在认证提交前准备token(令牌) //这里的帐号和密码 将来是由用户输入进去 UsernamePasswordToken token = new UsernamePasswordToken("zhangsan1", "111111"); try { //执行认证提交 subject.login(token); } catch (Exception e) { e.printStackTrace(); } //是否认证通过 boolean isAuth = subject.isAuthenticated(); System.out.println("是否认证通过:"+isAuth); }
3.2 散列算法
通常需要对密码 进行散列,常用的有md5、sha,
对md5密码,如果知道散列后的值可以通过穷举算法,得到md5密码对应的明文。
建议对md5进行散列时加salt(盐),进行加密相当 于对原始密码+盐进行散列。
正常使用时散列方法:
在程序中对原始密码+盐进行散列,将散列值存储到数据库中,并且还要将盐也要存储在数据库中。
如果进行密码对比时,使用相同 方法,将原始密码+盐进行散列,进行比对。
md5测试
package com.me.shiro.authentication;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
public class MD5Test {
public static void main(String[] args) {
//原始 密码
String source = "111111";
//盐
String salt = "qwerty";
//散列次数
int hashIterations = 2;
//上边散列1次:f3694f162729b7d0254c6e40260bf15c
//上边散列2次:36f2dfa24d0a9fa97276abbe13e596fc
//构造方法中:
//第一个参数:明文,原始密码
//第二个参数:盐,通过使用随机数
//第三个参数:散列的次数,比如散列两次,相当 于md5(md5(''))
Md5Hash md5Hash = new Md5Hash(source, salt, hashIterations);
String password_md5 = md5Hash.toString();
System.out.println(password_md5);
//第一个参数:散列算法
SimpleHash simpleHash = new SimpleHash("md5", source, salt, hashIterations);
System.out.println(simpleHash.toString());
}
}
3.2.2 自定义realm支持散列算法
需求:实际开发时realm要进行md5值(明文散列后的值)的对比。
3.2.2.1 新建realm(CustomRealmMd5)
package com.me.shiro.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
/**
* 自定义realm
*
* @author Administrator
*
*/
public class CustomRealmMD5 extends AuthorizingRealm {
@Override
public void setName(String name) {
// TODO Auto-generated method stub
super.setName("CustomRealmMD5");
}
// 用于认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// token是用户输入的
// 第一步从token中取出身份信息
String userCode = (String) token.getPrincipal();
// 第二步:根据用户输入的userCode从数据库查询
// ...
// 如果查询不到返回null
// 数据库中用户帐号是zhangsan
if (!"zhangsan".equals(userCode)) {
return null;
}
// 模拟从数据库查询到密码,散列值
String password = "f3694f162729b7d0254c6e40260bf15c";
// 从数据库获取salt
String salt = "qwerty";
// 上边散列值和盐对应的明文:111111
// 如果查询到返回认证信息AuthenticationInfo
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userCode, password,
ByteSource.Util.bytes(salt), this.getName());
return simpleAuthenticationInfo;
}
// 用于授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
return null;
}
}
3.2.2.2 在realm中配置凭证匹配器
<span style="font-size:14px;">[main] #定义凭证匹配器 credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher #散列算法 credentialsMatcher.hashAlgorithmName=md5 #散列次数 credentialsMatcher.hashIterations=1 #将凭证匹配器设置到realm customRealm=com.me.shiro.realm.CustomRealmMD5 customRealm.credentialsMatcher=$credentialsMatcher securityManager.realms=$customRealm</span>
3.2.2.3 测试
<span style="font-size:12px;">// 自定义realm实现散列值匹配 @Test public void testCustomRealmMD5(){ //创建securityManager工厂,通过ini配置文件创建securityManager工厂 Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm-md5.ini"); //创建SecurityManager org.apache.shiro.mgt.SecurityManager securityManager= factory.getInstance(); //将secrityManager设置当前的运行环境中 SecurityUtils.setSecurityManager(securityManager); //从SecurityUtils里创建一个subject Subject subject = SecurityUtils.getSubject(); //在认证提交前准备token(令牌) //这里的帐号和密码 将来是由用户输入进去 UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "211111"); try { //执行认证提交 subject.login(token); } catch (Exception e) { e.printStackTrace(); } //是否认证通过 boolean isAuth = subject.isAuthenticated(); System.out.println("是否认证通过:"+isAuth); } }</span>
相关文章推荐
- 查询新增序号列
- Android使用技巧------LocalBroadcastManager的使用
- c++排序算法
- shell去除换行和空格
- 专题四 Problem K
- Android视图加载到窗体的流程分析
- Java NIO系列教程(十一) Pipe
- 类与对象
- BT是如何下载的
- Python Class 重要基础知识篇
- VS2012程序打包部署详解:
- 《遇到百分之百的女孩》后感
- dark wonder代码解析1
- MLC固态硬盘,与入量是3000次P/E
- Linux - atexit()(注册终止)函数
- MLC固态硬盘,与入量是3000次P/E
- WebRTC Native APIs
- 也看网信办“搜索服务13条”新规
- 也看网信办“搜索服务13条”新规
- Python-开发之路-面向对象-进阶