SSM整合Shiro___自定义认证Realm

Posted zhangsonglin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM整合Shiro___自定义认证Realm相关的知识,希望对你有一定的参考价值。

加入依赖

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.21.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.14</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.21.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.21.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.21.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- shiro相关的依赖 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>

web.xml
在web.xml中注册shiro过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <!-- 中央处理器or前端控制器 -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 配置文件 -->
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <!-- 映射路径 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- spring框架提供的字符集过滤器 -->
    <!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <!-- 过滤器映射 -->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <!--file的匹配规则 -->
        <!--拦截url去除上下文后的映射路径/后的所有 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>



    <!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
         <!-- 设置true由servlet容器控制filter的生命周期 -->
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param> 
        <!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean -->
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>shiro</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

shiro的配置可以添加在spring的配置文件中。但是为了便于管理我们再单独创建一个shiro的配置文件,里面的Schema还是spring的。
shiro的配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 定义凭证匹配器 -->
    <bean
        class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
        id="credentialsMatcher">
        <!-- 配置散列算法 -->
        <property name="hashAlgorithmName" value="md5" />
        <!-- 配置散列次数 -->
        <property name="hashIterations" value="1024" />
    </bean>

    <!-- 注册自定义Realm -->
    <bean class="com.hrm.realm.MyRealm" id="myRealm">
        <!-- 配置凭证匹配器 -->
        <property name="credentialsMatcher" ref="credentialsMatcher" />
    </bean>
<!-- 注册SecurityManager -->
    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <!-- 配置自定义Realm -->
        <property name="realm" ref="myRealm"/>
    </bean>

<!-- 注册ShiroFilterFactoryBean 注意id必须和web.xml中注册的targetBeanName的值一致 -->
    <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"
        id="shiro">
        <!-- 注册SecurityManager -->
        <property name="securityManager" ref="securityManager" />
        <!-- 登录地址 如果用户请求的的地址是 login.do 那么会对该地址认证 -->
        <property name="loginUrl" value="/login.do" />
        <!-- 登录成功的跳转地址 -->
        <property name="successUrl" value="jsp/success.jsp" />
        <!-- 访问未授权的页面跳转的地址 -->
        <property name="unauthorizedUrl" value="jsp/refuse.jsp" />
<!-- 设置 过滤器链 -->
        <property name="filterChainDefinitions">
            <value>
                <!--加载顺序从上往下。
                    authc需要认证
                    anon可以匿名访问的资源
                 -->
                /login.do=authc
                /**=anon
            </value>
        </property>
    </bean>
</beans>

** Spring配置文件**

<context:component-scan base-package="com.hrm.service.impl"/>

    <!-- 引入配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />

    <!-- 设置DataSource -->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"
        id="dataSource">
        <property name="driverClass" value="$driver"></property>
        <property name="jdbcUrl" value="$url"></property>
        <property name="user" value="$user_name"></property>
        <property name="password" value="$password"></property>
    </bean>
    
    <!-- 整合Mybatis -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 设置对应的配置文件 -->
        <property name="configLocation"
            value="classpath:mybatis/mybatis-cfg.xml" />
        <!-- 设置别名 -->
        <property name="typeAliasesPackage" value="com.hrm.pojo" />
        <!-- 关联数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!-- 配置扫描的路径 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hrm.mapper" />
    </bean>

** SpringMVC配置文件**

<context:component-scan
        base-package="com.hrm.controller"></context:component-scan>
<mvc:annotation-driven/>

<!-- 防止资源文件被spring MVC拦截 -->
    <mvc:resources mapping="/img/**" location="/img/"
        cache-period="31556926" />
    <mvc:resources mapping="/js/**" location="/js/"
        cache-period="31556926" />
    <mvc:resources mapping="/css/**" location="/css/"
        cache-period="31556926" />

    <!-- 配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 设置前后缀 -->
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

** Mybatis全局配置文件**

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

自定义realm
自定义realm一定要继承AuthorizingRealm,可以重写doGetAuthenticationInfo来实现认证方法,可以重写doGetAuthorizationInfo来实现授权方法

MyRealm extends AuthorizingRealm

MyRealm


    /**
     * 认证的方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException 
        // 获取登录的账号
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        System.out.println("登录提交的账号:" + username);
        // 去数据库中查询
        List<User> list = userService.login(username);
        if (list == null || list.size() != 1) 
            return null;
        
        User user = list.get(0);
        System.out.println("user:" + user);
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPwd(), new SimpleByteSource(user.getSalt()),
                "myrealm");
    

Mapper接口和映射文件
技术图片

service
技术图片

Pojo
技术图片

控制层

package com.hrm.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class LoginController 

    /**
     * 在shiro中
     *   本方法在realm认证失败后会执行
     *   指定认证失败跳转的页面
     * @return
     */
    @RequestMapping("/login.do")
    public String login(HttpServletRequest request)
        Object msg = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        System.out.println("认证失败了...."+msg);
        return "redirect:/login.jsp";
    
    
    /**
     * 退出  注销
     * @return
     */
    @RequestMapping("/logout.do")
    public String logout()
        SecurityUtils.getSubject().logout();
        return "redirect:/login.jsp";
    
    
    
<form action="login.do" method="post">
    账号:<input type="text" name="username" ><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="提交">
</form>

数据表

技术图片

以上是关于SSM整合Shiro___自定义认证Realm的主要内容,如果未能解决你的问题,请参考以下文章

Shiro整合springboot以及自定义Realm

shiro学习笔记_0300_jdbcRealm和认证策略

SSM+Apache shiro--自定义realm

shiro学习笔记_0700_整合ssm

008-shiro与spring web项目整合认证授权session管理

shiro---Shiro认证授权案例讲解