shiro介绍
Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 Spring Security 做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。
使用shiro完成基本的登录
-
首先需要创建一个shiro配置文件(shiro.ini)
请填写以下内容
[users] zs=123 ls=123456 ww=123456789
这里先使用稍后说明具体作用
-
创建一个测试类
导入Junit和shiro依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.5.3</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
-
shiro使用基本步骤
//1.创建安全管理器对象 DefaultSecurityManager securityManager = new DefaultSecurityManager(); //2.设置给安全管理器设置realm securityManager.setRealm(new IniRealm()()); //3.SecurityUtils 全局安全工具类 SecurityUtils.setSecurityManager(securityManager); //4.关键对象,subject Subject subject = SecurityUtils.getSubject(); //5.创建令牌 UsernamePasswordToken token = new UsernamePasswordToken("zs", "123"); try { System.out.println("认证状态:" + subject.isAuthenticated()); subject.login(token); System.out.println("认证状态:" + subject.isAuthenticated()); } catch (UnknownAccountException e) { e.printStackTrace(); System.out.println("认证失败,用户名不存在"); } catch (IncorrectCredentialsException e) { e.printStackTrace(); System.out.println("认证失败,密码错误"); }
-
securityManager
相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理
-
subject
主体,可以看到主体可以是任何可以与应用交互的 “用户”
-
realm
可以有 1 个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等等;由用户提供;注意:Shiro 不知道你的用户 / 权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm
-
-
登录异常分析
- 用户名在配置文件中不存在时
- 抛出UnknownAccountException
- 用户名存在但密码错误时
- IncorrectCredentialsException
- 用户名和密码都正确
- subject.isAuthenticated()则会返回true
- 用户名在配置文件中不存在时
-
配置文件分析
- shiro的配置文件其实是方便使用者测试或入门使用
- [users]下代表着所有的用户
- 用户名=密码的键值对存储形式