shiro快速搭建

shiro快速搭建

在springmvc环境已经完成后,进行搭建
连接上了数据库,shiro需要数据的地方就调用service层就行

导入依赖(固定)

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.0</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.8.1</version>
</dependency>

在web.xml文件中配置shiroFilter(固定)

<!--  配置shiro的shirofilter-->
<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>

<!--  解决项目第一次重定向shiro产生的jsessionid的问题-->
 <session-config>
       <tracking-mode>COOKIE</tracking-mode>
 </session-config>

编写ehcache.xml(网上)

随便在网上找

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
       diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home – 用户主目录
       user.dir  – 用户当前工作目录
       java.io.tmpdir – 默认临时文件路径
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

配置spring的配置文件

编写一个文件叫做spring-shiro.xml

需要手写的部分:

  1. SecurityManager中的realm(s)的配置
  2. CacheManager中ehcache.xml路径的配置
  3. Realm中的class,以及是否需要密码加密
  4. Authenticator中的认证策略
  5. ShiroFilter中的登录、成功、未授权页面的配置。以及拦截器类的配置。
  6. 拦截器类的class
  7. 实例工厂的factory-bean和factory-method

完整文件如下:

<?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.xsd">
    
    <!--    shiro-->
    <!--    1. 配置securitymanager-->
    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <property name="cacheManager" ref="cacheManager"></property>
        <!--        <property name="realm" ref="jdbcRealm"></property>-->
        <property name="authenticator" ref="authenticator"></property>
        <property name="realms">
            <list>
                <ref bean="jdbcRealm"></ref>
                <ref bean="secondRealm"></ref>
            </list>
        </property>
    </bean>
    <!--    2. 配置cachemanager-->
    <!--    2.1 需要加入ehcache的依赖及配置文件-->
    <bean class="org.apache.shiro.cache.ehcache.EhCacheManager" id="cacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
    </bean>
    <!--    3.配置Realm-->
    <!--    3.1直接配置实现了realm接口的bean-->
    <bean class="com.nanda.realm.ShiroRealm" id="jdbcRealm">
        <!--        密码加密-->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--                以什么算法加密-->
                <property name="hashAlgorithmName" value="MD5"></property>
                <!--                加密次数-->
                <property name="hashIterations" value="1024"></property>
            </bean>
        </property>
    </bean>

    <bean class="com.nanda.realm.SecondRealm" id="secondRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="SHA1"></property>
                <property name="hashIterations" value="1024"></property>
            </bean>
        </property>
    </bean>

    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="authenticationStrategy">
            <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
        </property>
    </bean>
    <!--    4. 配置lifecyclebeanpostprocessor,可以自定义的来调用Spring IOC容器中shiro bean的生命周期方法-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
    <!--    5. 启用ioc 容器中使用shiro的注解 但是必须再配置了lifecyclebeanpostprocessor之后才能使用-->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"></bean>
    <!--    6.配置shirofilter-->
    <!--    6.1 id必须和web.xml文件中配置的delegatingfilterproxy的filtername一致
                delegatingfilterproxy实际上是filter的一个代理对象。
                默认情况下,spring会到ioc容器中查找和filter-name对应的filter bean,
                也可以通过targetBeanName的初始化参数来配置filter bean的id
        -->
    <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter">
        <property name="securityManager" ref="securityManager"></property>
        <property name="loginUrl" value="/login.jsp"></property>
        <property name="successUrl" value="/list.jsp"></property>
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
        <!--        6.2 配置哪些页面需要受保护,以及访问这些页面需要的权限
                6.2.1 anon可以被匿名访问
                6.2.2 authc必须认证(即登录)才可以访问的页面-
                6.2.3 logout:登出
                6.2.4 roles 角色过滤器-->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
    </bean>

    <bean class="com.nanda.controller.FilterChainDefinitionMapBuilder" id="filterChainDefinitionMapBuilder"></bean>

    <!--    配置一个bean,该bean实际上是一个Map,通过实例工厂方法的方式-->
    <bean factory-bean="filterChainDefinitionMapBuilder" factory-method="builderFilterChainDefinitionMap"
          id="filterChainDefinitionMap"></bean>
</beans>

配置SecurityManager

第一个是配置cacheManager(缓存处理器)

第二个是配置authenticator(身份认证)

第三个是配置realm(单个或多个)

<!--    1. 配置securitymanager-->
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
    <property name="cacheManager" ref="cacheManager"></property>
    <property name="authenticator" ref="authenticator"></property>
    <!--        <property name="realm" ref="jdbcRealm"></property>-->
    <property name="realms">
        <list>
            <ref bean="jdbcRealm"></ref>
            <ref bean="secondRealm"></ref>
        </list>
    </property>
</bean>

配置CacheManager

需要加入ehcache的依赖及配置文件

<!--    2. 配置cachemanager-->
<!--    2.1 需要加入ehcache的依赖及配置文件-->
<bean class="org.apache.shiro.cache.ehcache.EhCacheManager" id="cacheManager">
    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
</bean>

配置realm

mysql一般用MD5,oracle用SHA1

<!--    3.配置Realm-->
<!--    3.1直接配置实现了realm接口的bean-->
<bean class="com.nanda.realm.ShiroRealm" id="jdbcRealm">
    <!--        密码加密-->
    <property name="credentialsMatcher">
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <!--                以什么算法加密-->
            <property name="hashAlgorithmName" value="MD5"></property>
            <!--                加密次数-->
            <property name="hashIterations" value="1024"></property>
        </bean>
    </property>
</bean>

<bean class="com.nanda.realm.SecondRealm" id="secondRealm">
    <property name="credentialsMatcher">
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <property name="hashAlgorithmName" value="SHA1"></property>
            <property name="hashIterations" value="1024"></property>
        </bean>
    </property>
</bean>

配置authenticator

认证策略有FirstSuccessfulStrategy、AtLeastOneSuccessfulStrategy、AllSuccessfulStrategy

  • FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第 一个 Realm 身份验证成功的认证信息,其他的忽略;
  • AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和 FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信 息;
  • AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有 Realm身份验证成功的认证信息,如果有一个失败就失败了。
  • ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
    <!-- 认证策略-->
    <property name="authenticationStrategy">
        <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
    </property>
</bean>

配置lifecycleBeanPostProcessor

可以自定义的来调用Spring IOC容器中shiro bean的生命周期方法

<!--    4. 配置lifecyclebeanpostprocessor,可以自定义的来调用Spring IOC容器中shiro bean的生命周期方法-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>

配置DefaultAdvisorAutoProxyCreator

启用ioc 容器中使用shiro的注解 但是必须再配置了lifecyclebeanpostprocessor之后才能使用

<!--    5. 启用ioc 容器中使用shiro的注解 但是必须再配置了lifecyclebeanpostprocessor之后才能使用-->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"></bean>

配置shiroFilter

<!--    6.配置shirofilter-->
<!--    6.1 id必须和web.xml文件中配置的delegatingfilterproxy的filtername一致
            delegatingfilterproxy实际上是filter的一个代理对象。
            默认情况下,spring会到ioc容器中查找和filter-name对应的filter bean,
            也可以通过targetBeanName的初始化参数来配置filter bean的id
    -->
<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter">
    <property name="securityManager" ref="securityManager"></property>
    <!--登录、成功、未授权页面配置-->
    <property name="loginUrl" value="/login.jsp"></property>
    <property name="successUrl" value="/list.jsp"></property>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
    <!--        6.2 配置哪些页面需要受保护,以及访问这些页面需要的权限,通过filterChainDefinitionMap传递-->
    <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
</bean>

<!-- 自定义的返回map的类,为下面的bean做准备-->
<bean class="com.nanda.controller.FilterChainDefinitionMapBuilder" id="filterChainDefinitionMapBuilder"></bean>

<!--    配置一个bean,该bean实际上是一个Map,通过实例工厂方法的方式-->
<bean factory-bean="filterChainDefinitionMapBuilder" factory-method="builderFilterChainDefinitionMap"
      id="filterChainDefinitionMap"></bean>

编写拦截器类

以下内容需要从数据库内读取,然后添加进对应的map

public class FilterChainDefinitionMapBuilder {
    public LinkedHashMap<String, String> builderFilterChainDefinitionMap(){
        LinkedHashMap<String, String> map=new LinkedHashMap<>();

        map.put("/login.jsp","anon");
        map.put("/shiro/login","anon");
        map.put("/shiro/logout","logout");
        map.put("/user.jsp","anon,roles[user]");
        map.put("/admin.jsp","roles[admin]");
        map.put("/**","authc");

        return map;
    }
}

编写Controller

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

    @Autowired
    private ShiroService shiroService;

    //Session功能的测试
    //在service层,能直接通过SecurityUtils.getSubject().getSession()拿到Session
    @RequestMapping("/testShiroAnnotation")
    @RequiresRoles({"admin"})   //授权的注解
    public String testShiroAnnotation(HttpSession httpSession){
        httpSession.setAttribute("key","12345");
        shiroService.testMethod();
        return "redirect:/list.jsp";
    }
	
    //登录页面取到用户名密码
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        // 获取当前的 Subject. 调用 SecurityUtils.getSubject();
        Subject currentUser = SecurityUtils.getSubject();

        // 测试当前的用户是否已经被认证. 即是否已经登录.
        // 调动 Subject 的 isAuthenticated()
        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // rememberme
            token.setRememberMe(true);
            try {
                // 执行登录.
                currentUser.login(token);
            }
            // 所有认证时异常的父类.
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }
        return "redirect:/list.jsp";
    }
}

编写realm

public class ShiroRealm extends AuthorizingRealm {
	//用于认证的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo:" + token.hashCode());

        //1. 把AuthenticationToken转换成UsernamePasswordToken
        UsernamePasswordToken uptoken = (UsernamePasswordToken) token;

        //2. 把UsernamePasswordToken 中获取username
        String username = uptoken.getUsername();

        //3. 调用数据库的方法,从数据库中查询username对应的记录
        System.out.println("从数据库中获取username:" + username + "用户对应的信息");

        //4. 若用户不存在,则可以抛出UnknowAccountException异常
        if ("unknown".equals(username)) {
            throw new UnknownAccountException("用户不存在!");
        }

        //5. 根据用户信息的情况,决定是否需要抛出其他的AuthenticationException异常
        if ("locked".equals(username)) {
            throw new LockedAccountException("用户已被锁定!");
        }

        //6. 根据用户的情况,来构建AuthenticationInfo对象并返回
        //以下信息是从数据库中获取的
        //(1). principal:认证的实体信息。可以是username,也可以是数据表对应的用户的实体类对象
        //(2). credentials:密码,应该是从数据库中取出的
        //(3). realmName:当前realm对象的name。通过调用父类的getName()方法即可
        //(4). salt:盐值,使用ByteSource.Util.bytes生成
        Object principal = username;
        Object credentials = null;
        if (username.equals("user")){
            credentials = "098d2c478e9c11555ce2823231e02ec1";
        }else if (username.equals("admin")){
            credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
        }
        String realmName = getName();
        ByteSource salt = ByteSource.Util.bytes(username);   //用唯一的用户名生成盐值
        SimpleAuthenticationInfo info = null;
//        明文密码判断
//        info = new SimpleAuthenticationInfo(principal, credentials, realmName);
//        MD5、SHA1密码判断,盐值自行添加
        info = new SimpleAuthenticationInfo(principal, credentials,
                salt, realmName);
        return info;
    }

    //用于授权的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1. 从PrincipalCollection中获取登录用户的信息
        Object principal = principals.getPrimaryPrincipal();

        //2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库)
        Set<String> roles=new HashSet<>();
        roles.add("user");
        if ("admin".equals(principal)){
            roles.add("admin");
        }

        //3. 创建SimpleAuthorizationInfo,并设置其roles属性
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        //4. 返回SimpleAuthorizationInfo对象
        return info;
    }
    //模拟出密码的结果,项目中删除
    public static void main(String[] args) {
        String algorithmName = "MD5";   //加密的方式
        Object credentials = "123456";  //需要测试的加密的密码
        int hashIterations = 1024;     //加密次数
        ByteSource salt = ByteSource.Util.bytes("admin");   //用唯一的用户名生成盐值
        SimpleHash simpleHash = new SimpleHash(algorithmName, credentials, salt, hashIterations);
        System.out.println(simpleHash);
    }
}

编写前端页面

login.jsp

<body>
<%
    //如果登录认证或记住我,则直接跳转到主页
    Subject subject = SecurityUtils.getSubject();
    if(subject.isAuthenticated() || subject.isRemembered()){
        response.sendRedirect("list.jsp");
    }
%>
<form action="shiro/login" method="post">
    username:<input type="text" name="username"><br>
    password:<input type="text" name="password"><br>
    <input type="submit" value="提交"/>
</form>
</body>

list.jsp(成功页面)
记得引入jstl的头:

<%@ taglib prefix=“shiro” uri=“http://shiro.apache.org/tags” %>

<body>
<h4>list page</h4>
Welcome:<shiro:principal></shiro:principal>
<br><br>
<shiro:hasRole name="admin">
    <a href="admin.jsp">Admin page</a>
</shiro:hasRole>
<br><br>
<shiro:hasRole name="user">
    <a href="user.jsp">User page</a>
</shiro:hasRole>
<br><br>
<a href="${pageContext.request.contextPath}/shiro/logout">LogOut</a>
</body>

admin、user、unauthorized.jsp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值