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();
	}
相關文章
相關標籤/搜索