### 一、Shiro框架簡單介紹
Apache Shiro是Java的一個安全框架,旨在簡化身份驗證和授權。Shiro在JavaSE和JavaEE項目中都可以使用。它主要用來處理身份認證,授權,企業會話管理和加密等。Shiro的具體功能點如下:
(1)身份認證/登錄,驗證用戶是不是擁有相應的身份;?
(2)授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能做事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具有某個權限;?
(3)會話管理,即用戶登錄后就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通JavaSE環境的,也可以是如Web環境的;?
(4)加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲;?
(5)Web支持,可以非常容易的集成到Web環境;?
Caching:緩存,比如用戶登錄后,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率;?
(6)shiro支持多線程應用的并發驗證,即如在一個線程中開啟另一個線程,能把權限自動傳播過去;?
(7)提供測試支持;?
(8)允許一個用戶假裝為另一個用戶(如果他們允許)的身份進行訪問;?
(9)記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了。
文字描述可能并不能讓猿友們完全理解具體功能的意思。下面我們以登錄驗證為例,向猿友們介紹Shiro的使用。至于其他功能點,猿友們用到的時候再去深究其用法也不遲。
### 二、Shiro實例詳細說明
本實例環境:eclipse + maven?
本實例采用的主要技術:spring + springmvc + shiro
**2.1、依賴的包**
假設已經配置好了spring和springmvc的情況下,還需要引入shiro以及shiro集成到spring的包,maven依賴如下:
~~~
<!-- 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.2、定義shiro攔截器**
對url進行攔截,如果沒有驗證成功的需要驗證,然后額外給用戶賦予角色和權限。
自定義的攔截器需要繼承AuthorizingRealm并實現登錄驗證和賦予角色權限的兩個方法,具體代碼如下:
~~~
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.3、shiro配置文件**
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](http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html),更多詳細說明請訪問該鏈接。
**2.4、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.5、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.6、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.7、效果演示**
(1)如果未登錄前,輸入[http://localhost:8080/web_exception_project/index.jhtml](http://localhost:8080/web_exception_project/index.jhtml)會自動跳轉到[http://localhost:8080/web_exception_project/login.jhtml](http://localhost:8080/web_exception_project/login.jhtml)。
(2)如果登錄失敗和登錄成功:


(3)如果登錄成功,訪問[http://localhost:8080/web_exception_project/index.jhtml](http://localhost:8080/web_exception_project/index.jhtml)就可以到其對應的頁面了。

**2.8、源碼下載**
[http://download.csdn.net/detail/u013142781/9426670](http://download.csdn.net/detail/u013142781/9426670)
**2.9、我遇到的坑**
在本實例的調試里面遇到一個問題,雖然跟shiro沒有關系,但是也跟猿友們分享一下。?
就是ajax請求設置了“contentType : “application/json””,導致controller獲取不到username和password這兩個參數。?
后面去掉contentType : “application/json”,采用默認的就可以了。
具體原因可以瀏覽博文:[http://blog.csdn.net/mhmyqn/article/details/25561535](http://blog.csdn.net/mhmyqn/article/details/25561535)
- 前言
- Maven入門(含實例教程)
- Spirng+SpringMVC+Maven+Mybatis+MySQL項目搭建
- Dubbo分布式服務框架入門(附工程)
- mybaits入門(含實例教程和源碼)
- Zookeeper注冊中心的搭建
- Maven+Mybatis+Spring+SpringMVC實現分頁查詢(附源碼)
- Spring中@Transactional事務回滾(含實例詳細講解,附源碼)
- RabbitMQ消息隊列入門篇(環境配置+Java實例+基礎概念)
- Spring+EhCache緩存實例(詳細講解+源碼下載)
- Redis+Spring緩存實例(windows環境,附實例源碼及詳解)
- VMware Ubuntu安裝詳細過程
- VMware Tools (ubuntu系統)安裝詳細過程與使用
- 程序員一年工作經驗之談
- Shiro安全框架入門篇(登錄驗證實例詳解與源碼)
- Spring Security安全框架入門篇