SSM整合Shiro實現登陸認證完整demo(親寫)

前提:準備SSM項目,廢話不多言,直接上代碼。

一、添加依賴

    <!--shiro依賴-->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-quartz</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.3.2</version>
    </dependency>

二、配置web.xml



  <!-- 以過濾器的方式整合進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>
    <!-- targetBeanName值和spring的shiro的配置文件中bean的id值一致 -->
    <init-param>
      <param-name>targetBeanName</param-name>
      <param-value>shiroFilter</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <!-- 訪問任何url都會被shiro的過濾器過濾 -->
    <url-pattern>*.do</url-pattern>
  </filter-mapping>

三、添加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" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 配置自定義Realm -->
    <bean id="myRealm" class="com.xxf.shiro.UserRealm"/>

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
        <!-- 注入緩存管理器 -->
        <property name="cacheManager" ref="cacheManager"/>
        <!-- 注入session管理器 -->
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!-- 緩存管理器 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
    </bean>

    <!-- 會話管理器 -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- session的失效時長,單位毫秒 -->
        <property name="globalSessionTimeout" value="600000"/>
        <!-- 刪除失效的session -->
        <property name="deleteInvalidSessions" value="true"/>
    </bean>

    <!-- Shiro過濾器 核心-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,這個屬性是必須的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->
        <property name="loginUrl" value="/login.do"/>
        <!-- 權限認證失敗,則跳轉到指定頁面 -->
        <property name="unauthorizedUrl" value="/nopower.jsp"/>
        <!-- Shiro連接約束配置,即過濾鏈的定義 -->
        <property name="filterChainDefinitions">
            <value>
                <!--anon 表示匿名訪問,不需要認證以及授權-->
                /login.do=anon
                /dologin.do=anon
                /loginOut=logout
                <!--authc表示需要認證 沒有進行身份認證是不能進行訪問的-->
                /**=authc
            </value>
        </property>
    </bean>

    <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 開啓Shiro註解 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

</beans>

 四、添加spring-shiro.xml

<ehcache>
    <!--diskStore:緩存數據持久化的目錄 地址  -->
    <diskStore path="./ehcache" />
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

五、自定義的Realm

package com.xxf.shiro;

import com.xxf.model.AdminInfo;
import com.xxf.service.AdminResouceService;
import com.xxf.service.AdminService;
import org.apache.shiro.authc.*;
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 org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class UserRealm  extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminResouceService adminResouceService;

    /**
     * 功能描述: 授權
     * @Param: [principalCollection]
     * @Return: org.apache.shiro.authz.AuthorizationInfo
     * @Author: Administrator
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //用戶
        AdminInfo info = this.adminService.findByName(userName);
        if(info!=null){
            //根據用戶獲取用戶的角色
            Set<String> sroles = new HashSet<>();
            sroles.add(String.valueOf(info.getRoleId()));
            //賦值角色給simpleAuthorizationInfo
            simpleAuthorizationInfo.setRoles(sroles);
        }
        //根據用戶查詢用戶的權限
        Set<String> spermit = this.adminResouceService.selpremission(Integer.parseInt(info.getRoleId()));
        //授權
        simpleAuthorizationInfo.setStringPermissions(spermit);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份校驗--執行了goGetAuthenticationInfo...");
        //拿到用戶名
        String username = (String) token.getPrincipal();
        //根據用戶名數據庫中找到admin
        AdminInfo user = adminService.findByName(username);
        if (user == null) {
            throw new UnknownAccountException(); //沒有找到賬號
        }
        //交給AuthenticationRealm使用CredentialsMatcher進行密碼匹配
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //這裏要傳user,否則後面想拿到登錄的用戶信息,拿不到而報錯
                user.getPassword(), //密碼
                getName() //realm name
        );

        return authenticationInfo;
    }
}

六、Controller代碼(登錄)

 /**
     * 功能描述: 執行登陸驗證
     * @Param: [adminInfo]
     * @Return: java.lang.String
     * @Author: Administrator
     */
    @RequestMapping("/dologin")
    @ResponseBody
    public String login(@RequestBody AdminInfo adminInfo, HttpSession session){
        /*AdminInfo admin = this.adminService.checkPwdAndUserName(adminInfo);
        if(admin!=null){
            session.setAttribute("admin",admin);
            return "success";
        }
        return "error";*/

        String resuleMesage = "error";
        if (adminInfo != null ) {
            //初始化
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(adminInfo.getUserName(), adminInfo.getPassword());
            try {
                //登錄,即身份校驗,由通過Spring注入的UserRealm會自動校驗輸入的用戶名和密碼在數據庫中是否有對應的值
                subject.login(token);
                resuleMesage = "success";
                return resuleMesage;
                //return "redirect:index.do";
            }catch (Exception e){
                e.printStackTrace();
                resuleMesage = "未知錯誤,錯誤信息:" + e.getMessage();
            }
        } else {
            resuleMesage = "請輸入用戶名和密碼";
        }
        return resuleMesage;
    }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章