Java环境下shiro的测试

1.导入依赖的核心jar包

org.apache.shiro

shiro-core

1.3.2

2.认证程序

2.1 构建users配置文件 xxx.ini doGetAuthenticationInfo方法从该配置文件中获取数据与token中比对

[users]

test=123456

lisi=123456

测试程序

public class TestShiro {

public static void main(String[] args) {

//获取安全管理器工厂

IniSecurityManagerFactory iniSecurityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");

//获取安全管理器

SecurityManager securityManager = iniSecurityManagerFactory.getInstance();

//set认证器

SecurityUtils.setSecurityManager(securityManager);

//subject发起认证,获取subject

Subject subject = SecurityUtils.getSubject();

AuthenticationToken authenticationToken = new UsernamePasswordToken("test","123456");

//认证失败会抛出异常 密码:CredentialsException 账户:UnknownAccountException

try {

subject.login(authenticationToken);

} catch (AuthenticationException e) {

e.printStackTrace();

}

//当前subject是否认证通过

boolean authenticated = subject.isAuthenticated();

System.out.println(authenticated);

}

}

认证流程:

token携带身份和凭证信息--->subject发起认证--->SimpleAccountRealm(doGetAuthenticationInfo)获取配置文件中的用户信息---->CredentialsMatcher接口的实现类SimpleCredentialsMatcher:doCredentialsMatch方法对配置文件中的信息与token携带的信息进行比对--->认证成功或者失败。

3.Shiro框架中的关键对象:

AuthenticatingRealm //抽象类

//3.关键属性 该属性为凭证匹配器

CredentialsMatcher credentialsMatcher;

//1.该方法为抽象方法 其作用使用来获取数据

protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;

SimpleAccountRealm

//2.实现了AuthenticatingRealm抽象方法,用来获取配置文件中的用户信息,该类不做数据比对

SimpleCredentialsMatcher

//4.shiro中默认的凭证匹配器

public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

Object tokenCredentials = this.getCredentials(token);

Object accountCredentials = this.getCredentials(info);

return this.equals(tokenCredentials, accountCredentials);

}

必须要知道的类与接口,不然很难理解自定义Realm时属性为什么设置,使用哪种实现类方法等等:

以下代码或者截图贴出最重要的地方.

类继承关系

AuthenticatingRealm类

abstract class AuthenticatingRealm{

//凭证匹配器 接口,其实现类做数据比对

private CredentialsMatcher credentialsMatcher;

//获取配置文件中的用户信息

protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;

}

该抽象方法返回类型AuthenticationInfo接口:

AuthorizingRealm类 抽象方法后面测试授权时使用

abstract class AuthorizingRealm{

//

//该抽象方法 获取数据 获取授权的数据

protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection var1);

}

该抽象方法返回类型AuthorizationInfo接口:

CredentialsMatcher凭证匹配器接口:

其中:SimpleCredentialsMatcher是shiro中默认的凭证匹配器,其子类Hashxxx等都是做加密认证时使用

4.开发自定义Realm

public class MyRealm extends AuthenticatingRealm {

//实现抽象方法doGetAuthenticationInfo

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)

throws AuthenticationException {

String principal =(String) authenticationToken.getPrincipal();

//查库取回User对象

SqlSession sqlSession = null;

try {

sqlSession = MySqlSession.getSqlSession();

} catch (IOException e) {

e.printStackTrace();

}

UserMapper mapper = sqlSession.getMapper(UserMapper.class);

User user = mapper.queryUserByUserName(principal);

AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal,user.getPassword(),this.getName());

return authenticationInfo;

}

}

4.1通知shiro使用自定义realm

[main]

#自定义 realm

customRealm=com.nyist.test.MyRealm

#将realm设置到securityManager

securityManager.realms=$customRealm

注意:需要导入一个jar

commons-logging

commons-logging

1.2

5.shiro的加密认证方式

5.1.使用shiro提供的Md5Hash类为一个字符串加密进行测试

public class TestMD5 {

public static void main(String[] args) {

Md5Hash hash = new Md5Hash("123456","salt",1024);

String s = hash.toHex();

System.out.println(s);

//a18d2133f593d7b0e3ed488560404083

}

}

5.2.修改配置文件,加入凭证匹配器的相关配置

[main]

#自定义凭证匹配器

hashedCredentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher

#凭证匹配器通知AuthenticatingRealm,由于自定义realm继承了AuthenticatingRealm,直接设置已有的MyRealm属性即可

#自定义 realm

customRealm=com.nyist.test.MyRealm

customRealm.credentialsMatcher=$hashedCredentialsMatcher

hashedCredentialsMatcher.hashAlgorithmName=MD5

hashedCredentialsMatcher.hashIterations=1024

#将realm设置到securityManager .realms使用set方式赋值

securityManager.realms=$customRealm

坑:Caused by: java.lang.IllegalStateException: Required 'hashAlgorithmName' property has not been set. This is required to execute the hashing algorithm.

HashedCredentialsMatcher类中set方法非常规,set方法为:setHashAlgorithmName

为什么这么设置凭证匹配器?

自定义MyRealm extends AuthorizingRealm,实现两个抽象方法

AuthenticationInfo doGetAuthenticationInfo()来自于AuthenticatingRealm类,获取认证数据

AuthorizationInfo doGetAuthorizationInfo()来自于AuthorizingRealm类,获取授权数据

public class MyRealm extends AuthorizingRealm {

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)

throws AuthenticationException {

String principal =(String) authenticationToken.getPrincipal();

//userDao.queryUserByUserName

SqlSession sqlSession = null;

try {

sqlSession = MySqlSession.getSqlSession();

} catch (IOException e) {

e.printStackTrace();

}

UserMapper mapper = sqlSession.getMapper(UserMapper.class);

User user = mapper.queryUserByUserName(principal);

/*

* ByteSource.Util.bytes("salt") 盐字段来自数据库,凭证匹配器不能写死盐值

* 安全管理器可以获取到AuthenticationInfo中的盐值 对用户界面的凭证加密

* */

AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal,user.getPassword(),ByteSource.Util.bytes("salt"),this.getName());

return authenticationInfo;

}

@Override

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//获取身份信息 Principal用户名、手机号、邮箱地址等 一个主体可以有多个身份,但是必须有一个主身份(Primary Principal)

String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();

/*

* 用户----角色----权限

* 中间表 中间表

* */

//由primaryPrincipal查库--->获得角色info ---->获取权限info

SqlSession sqlSession = null;

try {

sqlSession = MySqlSession.getSqlSession();

} catch (IOException e) {

e.printStackTrace();

}

UserMapper mapper = sqlSession.getMapper(UserMapper.class);

User user = mapper.queryUserByUserName(primaryPrincipal);

//测试基于角色的授权

/*if (primaryPrincipal.equals(user.getUsername())){

// class SimpleAuthorizationInfo implements AuthorizationInfo

SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

authorizationInfo.addRole("super");

return authorizationInfo;

}*/

//测试基于资源的授权

if(primaryPrincipal.equals(user.getUsername())){

SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

authorizationInfo.addStringPermission("user:delete");

authorizationInfo.addStringPermissions(Arrays.asList("admin:delete","admin:add"));

return authorizationInfo;

}

return null;

}

}

一张图看懂认证授权关系:

授权的api

基于角色 //判断当前主体是否包含此角色

boolean b = subject.hasRole("super");

List list = Arrays.asList("super", "admin");

//判断当前主体是否包含某个角色

boolean[] booleans = subject.hasRoles(list);

//判断当前主体是否包含全部的角色

boolean b = subject.hasAllRoles(list);

基于资源 boolean b = subject.isPermitted("admin:delete");

String[] strs={"admin:delete", "admin:add"};

boolean[] permitted = subject.isPermitted(strs);

boolean permittedAll = subject.isPermittedAll(strs);

资源权限的标识符

权限字符串的规则是:“资源标识符:操作:资源实例标识符”,意思是对哪个资源的哪个实例具有什么操作,“:”是资源/操作/实例的分割符,权限字符串也可以使用*通配符。

例子:

用户创建权限:user:create,或user:create:*

用户修改实例001的权限:user:update:001

用户实例001的所有权限:user:*:001

java用户的授权及验证_Java环境下shiro的测试-认证与授权相关推荐

  1. java山寨qq账号密码验证_Java实战-山寨QQ

    功能: 1.登录界面QQClientLogin.java,好友界面QQFriendList.java,聊天界面QQChar.java 2.当用户点击登录后,把账号密码发送给QQserver.java, ...

  2. java web shiro_javase和javaweb环境下shiro的搭建

    shiro-1 javase环境下搭建shiro 1.导入jar包 2.配置文件:存储临时文件 shiro.ini文件:存储数据,用户名,密码,角色,权限 3.代码 // 1.获取安全管理器 Fact ...

  3. Java练习-----2.对Windows和Linux环境下输入的文件路径格式进行校验

    1.需求 Windows环境下路径格式只能为 D:\Desktop\source Linux环境下路径格式只能为 /data/source 2.结果展示 Linux环境下运行成功,懒得开虚拟机,就不展 ...

  4. shiro安全框架初识--shiro简介、认证与授权

    1.shiro安全框架 1.1.什么是权限管理 基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只 ...

  5. shiro+jwt进行认证和授权的解决方案代码实例

    文章目录 token类 自定义realm 自定义的jwtFilter用于访问拦截: shiroconfig controller vo对象 测试 jwt和shiro框架就不多介绍了,直接上实例代码吧. ...

  6. SSM整合Shiro进行登陆认证和授权详细配置

    本篇博客将进行详细介绍Shiro+Spring+SpringMVC+Mybatis+数据库整合并进行登陆认证和授权详细配置. SSM的整合可以参考:https://blog.csdn.net/a745 ...

  7. SpringBoot整合Shiro实现登录认证和授权CHCache

    文章目录 一. springboot实现普通登录 1 添加依赖 2 编写配置文件 3 新建实体类和mapper 4 编写业务层代码 5 编写控制器 6 编写启动类 7 编写登录页面和主页面 二. sp ...

  8. 各种环境下的渗透测试

    转载来源:http://drops.wooyun.org/tips/411 getshell: 找到切入点后,首先是要弹个shell,一般我用back.py 配合nc使用,nc监听端口就不说了. ba ...

  9. Java猜数游戏怎么验证_Java实现猜数游戏

    利用Math.random()方法产生1~100的随机整数,利用JOptionPane.showInputDialog()方法产生一个输入对话框,用户可以输入所猜的数.若所猜的数比随机生成的数大,则显 ...

最新文章

  1. R语言使用caret包的confusionMatrix函数计算混淆矩阵、使用编写的自定义函数可视化混淆矩阵(confusion matrix)
  2. Linux文件系统中文版,Linux 文件系统-Go语言中文社区
  3. AtCoder Beginner Contest 131 F - Must Be Rectangular!
  4. oracle在线中文文档,Oracle TopLink
  5. 教育资源数字化 计算机和通讯,《计算机网络技术课程数字化资源开发研究》.doc...
  6. struts的比较标签,在使用时,与测试时需要留心。
  7. React技术栈梳理
  8. matlab接收端CRC校验编码,循环冗余校验码CRC文献综述和参考文献
  9. xbox360 无线手柄 通过cmd_vel控制小乌龟运动
  10. bada开发tips
  11. 基于宏指令下的威纶通配方功能(RW位控制)
  12. Java并发 - 线程的生命周期
  13. html5导航栏向应折叠,超实用!网站导航栏设计形式总结
  14. 美国人在世界各地随意干扰别国内政,发动战争,你认为这样做得对吗?
  15. 盘点Java技术在生活中的10大应用
  16. ssm框架的简单介绍
  17. 泛读论文:Person-reID 行人重识别合集
  18. 手机中的便签如何保存到另一手机中
  19. setContentType总结
  20. java暂挂状态,Guarded Suspension(保护性暂挂)模式

热门文章

  1. PHP 中setcookie,用PHP如何设置setcookie?
  2. python例题求乘客等车时间_python编程例题
  3. CSP小明种苹果(C语言)
  4. 每行输出5个java_在JAVA中,如何实现输出的每行只显示5个数
  5. 干货|做一个懂得激励的团队经理
  6. 新版spyder中如何设置脚本文件共同使用同一个Variable explorer 中数据
  7. Docker学习与总结(二)
  8. USB 4.0有什么用,和雷电3有什么区别,USB 4.0什么时候上市
  9. 晶体工作原理介绍【转】
  10. ppt未保存+已关闭,可以恢复!