Apache Shiro是Java的一個安全框架,旨在簡化身份驗證和受權。Shiro在JavaSE和JavaEE項目中均可以使用。它主要用來處理身份認證,受權,企業會話管理和加密等。Shiro的具體功能點以下:javascript
(1)身份認證/登陸,驗證用戶是否是擁有相應的身份;
(2)受權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能作事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具備某個權限;
(3)會話管理,即用戶登陸後就是一次會話,在沒有退出以前,它的全部信息都在會話中;會話能夠是普通JavaSE環境的,也能夠是如Web環境的;
(4)加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲;
(5)Web支持,能夠很是容易的集成到Web環境;
Caching:緩存,好比用戶登陸後,其用戶信息、擁有的角色/權限沒必要每次去查,這樣能夠提升效率;
(6)shiro支持多線程應用的併發驗證,即如在一個線程中開啓另外一個線程,能把權限自動傳播過去;
(7)提供測試支持;
(8)容許一個用戶僞裝爲另外一個用戶(若是他們容許)的身份進行訪問;
(9)記住我,這個是很是常見的功能,即一次登陸後,下次再來的話不用登陸了。html
文字描述可能並不能讓猿友們徹底理解具體功能的意思。下面咱們以登陸驗證爲例,向猿友們介紹Shiro的使用。至於其餘功能點,猿友們用到的時候再去深究其用法也不遲。java
本實例環境:eclipse + maven
本實例採用的主要技術:spring + springmvc + shirojquery
2.一、依賴的包web
假設已經配置好了spring和springmvc的狀況下,還須要引入shiro以及shiro集成到spring的包,maven依賴以下:ajax
<!-- Spring 整合Shiro須要的依賴 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.1</version> </dependency>
2.二、定義shiro攔截器spring
對url進行攔截,若是沒有驗證成功的須要驗證,而後額外給用戶賦予角色和權限。數據庫
自定義的攔截器須要繼承AuthorizingRealm並實現登陸驗證和賦予角色權限的兩個方法,具體代碼以下:apache
package com.luo.shiro.realm;
import java.util.HashSet; import java.util.Set; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import com.luo.util.DecriptUtil; public class MyShiroRealm extends AuthorizingRealm { //這裏由於沒有調用後臺,直接默認只有一個用戶("luoguohui","123456") private static final String USER_NAME = "luoguohui"; private static final String PASSWORD = "123456"; /* * 受權 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Set<String> roleNames = new HashSet<String>(); Set<String> permissions = new HashSet<String>(); roleNames.add("administrator");//添加角色 permissions.add("newPage.jhtml"); //添加權限 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(permissions); return info; } /* * 登陸驗證 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; if(token.getUsername().equals(USER_NAME)){ return new SimpleAuthenticationInfo(USER_NAME, DecriptUtil.MD5(PASSWORD), getName()); }else{ throw new AuthenticationException(); } } }
2.三、shiro配置文件json
spring-shiro.xml文件內容以下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-lazy-init="true"> <description>Shiro Configuration</description> <!-- Shiro's main business-tier object for web-enabled applications --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myShiroRealm" /> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- 項目自定義的Realm --> <bean id="myShiroRealm" class="com.luo.shiro.realm.MyShiroRealm"> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jhtml" /> <property name="successUrl" value="/loginsuccess.jhtml" /> <property name="unauthorizedUrl" value="/error.jhtml" /> <property name="filterChainDefinitions"> <value> /index.jhtml = authc /login.jhtml = anon /checkLogin.json = anon /loginsuccess.jhtml = anon /logout.json = anon /** = authc </value> </property> </bean> <!-- 用戶受權信息Cache --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <!-- 保證明現了Shiro內部lifecycle函數的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- AOP式方法級權限檢查 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> </beans>
這裏有必要說清楚」shiroFilter」 這個bean裏面的各個屬性property的含義:
(1)securityManager:這個屬性是必須的,沒什麼好說的,就這樣配置就好。
(2)loginUrl:沒有登陸的用戶請求須要登陸的頁面時自動跳轉到登陸頁面,可配置也可不配置。
(3)successUrl:登陸成功默認跳轉頁面,不配置則跳轉至」/」,通常能夠不配置,直接經過代碼進行處理。
(4)unauthorizedUrl:沒有權限默認跳轉的頁面。
(5)filterChainDefinitions,對於過濾器就有必要詳細說明一下:
1)Shiro驗證URL時,URL匹配成功便再也不繼續匹配查找(因此要注意配置文件中的URL順序,尤爲在使用通配符時),故filterChainDefinitions的配置順序爲自上而下,以最上面的爲準
2)當運行一個Web應用程序時,Shiro將會建立一些有用的默認Filter實例,並自動地在[main]項中將它們置爲可用自動地可用的默認的Filter實例是被DefaultFilter枚舉類定義的,枚舉的名稱字段就是可供配置的名稱
3)一般可將這些過濾器分爲兩組:
anon,authc,authcBasic,user是第一組認證過濾器
perms,port,rest,roles,ssl是第二組受權過濾器
注意user和authc不一樣:當應用開啓了rememberMe時,用戶下次訪問時能夠是一個user,但毫不會是authc,由於authc是須要從新認證的
user表示用戶不必定已經過認證,只要曾被Shiro記住過登陸狀態的用戶就能夠正常發起請求,好比rememberMe
說白了,之前的一個用戶登陸時開啓了rememberMe,而後他關閉瀏覽器,下次再訪問時他就是一個user,而不會authc
4)舉幾個例子
/admin=authc,roles[admin] 表示用戶必需已經過認證,並擁有admin角色才能夠正常發起’/admin’請求
/edit=authc,perms[admin:edit] 表示用戶必需已經過認證,並擁有admin:edit權限才能夠正常發起’/edit’請求
/home=user 表示用戶不必定須要已經經過認證,只須要曾經被Shiro記住過登陸狀態就能夠正常發起’/home’請求
5)各默認過濾器經常使用以下(注意URL Pattern裏用到的是兩顆星,這樣才能實現任意層次的全匹配)
/admins/=anon 無參,表示可匿名使用,能夠理解爲匿名用戶或遊客
/admins/user/=authc 無參,表示需認證才能使用
/admins/user/=authcBasic 無參,表示httpBasic認證
/admins/user/=user 無參,表示必須存在用戶,當登入操做時不作檢查
/admins/user/=ssl 無參,表示安全的URL請求,協議爲https
/admins/user/=perms[user:add:]
參數可寫多個,多參時必須加上引號,且參數之間用逗號分割,如/admins/user/=perms[「user:add:,user:modify:*」]
當有多個參數時必須每一個參數都經過纔算經過,至關於isPermitedAll()方法
/admins/user/=port[8081]
當請求的URL端口不是8081時,跳轉到schemal://serverName:8081?queryString
其中schmal是協議http或https等,serverName是你訪問的Host,8081是Port端口,queryString是你訪問的URL裏的?後面的參數
/admins/user/=rest[user]
根據請求的方法,至關於/admins/user/=perms[user:method],其中method爲post,get,delete等
/admins/user/=roles[admin]
參數可寫多個,多個時必須加上引號,且參數之間用逗號分割,如/admins/user/=roles[「admin,guest」]
當有多個參數時必須每一個參數都經過纔算經過,至關於hasAllRoles()方法
上文參考了http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html,更多詳細說明請訪問該連接。
2.四、web.xml配置引入對應的配置文件和過濾器
<!-- 讀取spring和shiro配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value> </context-param> <!-- shiro過濾器 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.jhtml</url-pattern> <url-pattern>*.json</url-pattern> </filter-mapping>
2.五、controller代碼
package com.luo.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.alibaba.druid.support.json.JSONUtils; import com.luo.errorcode.LuoErrorCode; import com.luo.exception.BusinessException; import com.luo.util.DecriptUtil; @Controller public class UserController { @RequestMapping("/index.jhtml") public ModelAndView getIndex(HttpServletRequest request) throws Exception { ModelAndView mav = new ModelAndView("index"); return mav; } @RequestMapping("/exceptionForPageJumps.jhtml") public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception { throw new BusinessException(LuoErrorCode.NULL_OBJ); } @RequestMapping(value="/businessException.json", method=RequestMethod.POST) @ResponseBody public String businessException(HttpServletRequest request) { throw new BusinessException(LuoErrorCode.NULL_OBJ); } @RequestMapping(value="/otherException.json", method=RequestMethod.POST) @ResponseBody public String otherException(HttpServletRequest request) throws Exception { throw new Exception(); } //跳轉到登陸頁面 @RequestMapping("/login.jhtml") public ModelAndView login() throws Exception { ModelAndView mav = new ModelAndView("login"); return mav; } //跳轉到登陸成功頁面 @RequestMapping("/loginsuccess.jhtml") public ModelAndView loginsuccess() throws Exception { ModelAndView mav = new ModelAndView("loginsuccess"); return mav; } @RequestMapping("/newPage.jhtml") public ModelAndView newPage() throws Exception { ModelAndView mav = new ModelAndView("newPage"); return mav; } @RequestMapping("/newPageNotAdd.jhtml") public ModelAndView newPageNotAdd() throws Exception { ModelAndView mav = new ModelAndView("newPageNotAdd"); return mav; } /** * 驗證用戶名和密碼 * @param String username,String password * @return */ @RequestMapping(value="/checkLogin.json",method=RequestMethod.POST) @ResponseBody public String checkLogin(String username,String password) { Map<String, Object> result = new HashMap<String, Object>(); try{ UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(password)); Subject currentUser = SecurityUtils.getSubject(); if (!currentUser.isAuthenticated()){ //使用shiro來驗證 token.setRememberMe(true); currentUser.login(token);//驗證角色和權限 } }catch(Exception ex){ throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE); } result.put("success", true); return JSONUtils.toJSONString(result); } /** * 退出登陸 */ @RequestMapping(value="/logout.json",method=RequestMethod.POST) @ResponseBody public String logout() { Map<String, Object> result = new HashMap<String, Object>(); result.put("success", true); Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); return JSONUtils.toJSONString(result); } }
上面代碼,咱們只須要更多地關注登陸驗證和退出登陸的代碼。
其中DecriptUtil.MD5(password),對密碼進行md5加密解密是我本身寫的工具類DecriptUtil,對應MyShiroRealm裏面的登陸驗證裏面也有對應對應的方法。
另外,BusinessException是我本身封裝的異常類。
最後會提供整個工程源碼供猿友下載,裏面包含了全部的代碼。
2.六、login.jsp代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <script src="<%=request.getContextPath()%>/static/bui/js/jquery-1.8.1.min.js"></script> </head> <body> username: <input type="text" id="username"><br><br> password: <input type="password" id="password"><br><br> <button id="loginbtn">登陸</button> </body> <script type="text/javascript"> $('#loginbtn').click(function() { var param = { username : $("#username").val(), password : $("#password").val() }; $.ajax({ type: "post", url: "<%=request.getContextPath()%>" + "/checkLogin.json", data: param, dataType: "json", success: function(data) { if(data.success == false){ alert(data.errorMsg); }else{ //登陸成功 window.location.href = "<%=request.getContextPath()%>" + "/loginsuccess.jhtml"; } }, error: function(data) { alert("調用失敗...."); } }); }); </script> </html>
2.七、效果演示
(1)若是未登陸前,輸入http://localhost:8080/web_exception_project/index.jhtml會自動跳轉到http://localhost:8080/web_exception_project/login.jhtml。
(2)若是登陸失敗和登陸成功:
(3)若是登陸成功,訪問http://localhost:8080/web_exception_project/index.jhtml就能夠到其對應的頁面了。
2.八、源碼下載
http://download.csdn.net/detail/u013142781/9426670
2.九、我遇到的坑
在本實例的調試裏面遇到一個問題,雖然跟shiro沒有關係,可是也跟猿友們分享一下。
就是ajax請求設置了「contentType : 「application/json」」,致使controller獲取不到username和password這兩個參數。
後面去掉contentType : 「application/json」,採用默認的就能夠了。
具體緣由能夠瀏覽博文:http://blog.csdn.net/mhmyqn/article/details/25561535