Shiro简介

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.java

        Apache Shiro是一个强大的、易使用的java安全框架。它包括了认证、受权、加密和session管理。经过Shiro的简单易理解的API,你能够快速的给很小的电话应用、和很大的企业应用加安全措施。web

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/2018398apache

1.4 入门

        a)下载:
缓存

          官方网站下载jar包:http://shiro.apache.org/安全

          maven下载:
session

<!-- shiro -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-all</artifactId>
			<version>${shiro-Version}</version>
		</dependency>

        b)使用
app

/**
	 * 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 {
			// 五、登陆:只认证(只会在login时,才去数据库、缓存中调用)
			subject.login(token);
			// 六、受权:每次权限验证都会去数据源、缓存中调用
			System.out.println(subject.hasRole("admin"));
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		Assert.assertEquals(true, subject.isAuthenticated());
		subject.logout();
	}
相关文章
相关标签/搜索