shiro简介
1.1 简述
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.
Apache Shiro是一个强大的、易使用的java安全框架。它包括了认证、授权、加密和session管理。通过Shiro的简单易理解的API,你可以快速的给很小的电话应用、和很大的企业应用加安全措施。
1.2 为什么要用shiro
通常我们在做项目安全措施的时候,都会选择RBAC(role based access controller),而在真正的实现过程中,还需要做其它考虑。例如:分布式,oauth,单点登录...这个就是高可复用性的部分,如果团队规模不够,自己开发和维护一个这样的框架,想必是很麻烦的。apache shiro就是很好的选择,这种轻量级的框架,正好适合我们的需要。(关于 RBAC的讨论:http://www.iteye.com/magazines/82#72)
1.3 源码学习
可以根据涛哥的专题:http://jinnianshilongnian.iteye.com/blog/2018398
1.4 入门
a)下载:
官方网站下载jar包:http://shiro.apache.org/
maven下载:
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>${shiro-Version}</version>
</dependency>
b)使用
/**
* shiro学习
*/
@Test
public void shiroTest() {
// 1.工厂类,主要用来解析配置文件,初始化SecuritManager<全局唯一>
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2. SecuritManager:安全管理器,所有操作:认证、授权等都在其中完成<全局唯一>
SecurityManager securityManager = factory.getInstance();
// 3. SecuritUtils:一个工具类,保证了每次调用的SecuritManager都一样
SecurityUtils.setSecurityManager(securityManager);
// 4. Subject:一个访问主体(和web中的session类似,都存放在threadlocal中)<每个线程一个>
Subject subject = SecurityUtils.getSubject();
// 5. 用户和密码:用于认证、授权
UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");
try {
// 5、登录:只认证(只会在login时,才去数据库、缓存中调用)
subject.login(token);
// 6、授权:每次权限验证都会去数据源、缓存中调用
System.out.println(subject.hasRole("admin"));
} catch (AuthenticationException e) {
e.printStackTrace();
}
Assert.assertEquals(true, subject.isAuthenticated());
subject.logout();
}