1. 程式人生 > >Shiro安全框架入門篇(登入驗證例項詳解與原始碼)

Shiro安全框架入門篇(登入驗證例項詳解與原始碼)

一、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()方法

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、效果演示

(2)如果登入失敗和登入成功:

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

2.8、原始碼下載

2.9、我遇到的坑

在本例項的除錯裡面遇到一個問題,雖然跟shiro沒有關係,但是也跟猿友們分享一下。
就是ajax請求設定了“contentType : “application/json””,導致controller獲取不到username和password這兩個引數。
後面去掉contentType : “application/json”,採用預設的就可以了。