1. 程式人生 > >關於spring mvc + shiro 的登陸認證

關於spring mvc + shiro 的登陸認證

簡單介紹一下shiro 是apache 下的一個框架,其目的在於精簡系統登陸認證和許可權控制的開發。更好的維護系統的安全性。

在專案已經搭建好的前提下:
1.首先準備shiro 的相關jar 包

這裡寫圖片描述

當然也可以用一個包來代替上面所有的包shiro-all.jar
載入build path 載入到專案中去

  1. 在web.xml中配置filter 攔截器
<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>/*</url-pattern> </filter-mapping>

3.建立applicationContext-shiro.xml 要使這個檔案在web.xml中載入
這裡寫圖片描述

4.配置applicationContext-shiro.xml 檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-lazy-init="false">
<!-- Root Context: defines shared resources visible to all other web components --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean> <!-- 快取管理 --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean> <!--登陸驗證驗證 --> <bean id="shiroLocalRealm" class="com.model.interceptor.ShiroLocalRealm" /> <!-- Shiro安全管理器 --> <bean id="securityManager"class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- 本地認證 --> <property name="realm" ref="shiroLocalRealm" /> <property name="cacheManager" ref="cacheManager"></property> </bean> <!-- Shiro主過濾器本身功能十分強大,其強大之處就在於它支援任何基於URL路徑表示式的、自定義的過濾器的執行 Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支援 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全介面,這個屬性是必須的 --> <property name="securityManager" ref="securityManager"></property> <!-- 要求登入時的連結(登入頁面地址),非必須的屬性,預設會自動尋找Web工程根目錄下的"/login.jsp"頁面 --> <property name="loginUrl" value="/login.jsp"></property> <!-- 登入成功後要跳轉的連線(本例中此屬性用不到,因為登入成功後的處理邏輯在LoginController裡硬編碼) --> <!-- <property name="successUrl" value="/" ></property> --> <!-- 使用者訪問未對其授權的資源時,所顯示的連線 --> <property name="unauthorizedUrl" value="/"></property> <property name="filterChainDefinitions"> <value> /static/*=anon /loginSave=anon /**=authc </value> </property> </bean> </beans>

5.編寫shiro後臺登入驗證的程式碼


1.訪問登入的Controller
// 登入驗證shiro
    @RequestMapping(value = "/loginSave", method = RequestMethod.POST)
    public void loginSave(
            @RequestParam(value = "passport") String passport,
            @RequestParam(value = "pwd") String pwd, 
            HttpSession session,
            HttpServletResponse response, 
            HttpServletRequest request
    )throws Exception 
    {
        response.setContentType("application/text; charset=UTF-8");

        //獲取主體物件
        Subject currentUser = SecurityUtils.getSubject();

        //shiro容器認證
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(passport, pwd);
            currentUser.login(token);
        }

        // 若認證異常,不會執行下面的語句
        //session 儲存使用者資訊和常用的資訊
        response.getWriter().print(1);
    }





2.登入校驗的類
package com.model.interceptor;

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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class ShiroLocalRealm extends AuthorizingRealm {

    /**
     * 授權資訊
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 認證資訊
     */
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String userName = token.getUsername();
        String password = String.valueOf(token.getPassword());

        int status = 0;
        if(("123").equals(userName)&&"123".equals(password)){
            status=1;
        }
        if (status == 1) {
            AuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, getName());
            clearCache(info.getPrincipals());
            return info;
        }
        return null;
    }
}

3. 關閉shiro, 退出登入

    @RequestMapping(value = "/out", method = RequestMethod.GET)
    public ModelAndView out(HttpSession session, HttpServletResponse response,
            HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        // session 登出
        // session.invalidate();  
        try {
            currentUser.logout();  
        } catch (Exception e) {
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/login");
        return modelAndView;
    }