Shiro框架03(SSM结合shiro、SessionManager管理、rememberMe功能的实现)

Shiro框架03

1.SSM结合Shiro

[1]web.xml
<!--使用过滤器连接Shiro-->
    <!--注册了DelegatingFilterProxy 使用代理把servlet容器中filter和spring中的bean进行连接-->
    <filter>
        <filter-name>shiro</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <!--设置为true之后可以使用过滤器中的初始化,销毁等方法-->
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--给注册了的bean对象起一个名称,值为shiroFilter-->
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>shiroFilter</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiro</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
[2]applicationContext-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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--A、注册凭证匹配器-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!--配置加密方式-->
        <property name="hashAlgorithmName" value="md5"></property>
        <!--配置迭代次数-->
        <property name="hashIterations" value="2"></property>
    </bean>
    <!--B、注册自定义Realm-->
    <bean id="userRealm" class="cn.qt.realm.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>
    <!--C、注册securityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--设置自定义realm-->
        <property name="realms" ref="userRealm"></property>
        <!--设置会话管理器-->
        <property name="sessionManager" ref="sessionManager"></property>
    </bean>
    <!--D、注册ShiroFliterFactoryBean对象-->
    <!--注意:id必须和web.xml中  使用过滤器连接filter  的targetBeanName保持一致-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <!--登录URL-->
        <property name="loginUrl" value="/adminlogin"></property>
        <!--登录成功地址-->
        <property name="successUrl" value="findMoreMenus"></property>
        <!--登录失败地址-->
        <property name="unauthorizedUrl" value="error"></property>

        <!--设置过滤器链的属性-->
        <property name="filterChainDefinitions">
            <!--authc:拦截指定路径   anon:放行-->
            <value>
                /adminlogin=authc
                <!--配置退出的过滤器 如果没有配置退出的页面,默认是退到项目默认网页中index.jsp-->

                <!--记住我的路径-->
                /findMoreMenus=user

                /loginOut=logout
                /** =anon   
                <!-- */ 上一行代码的意思是其他的所有请求均不拦截 -->
            </value>
        </property>
    </bean>

    <!--配置退出页面-->
    <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="login"></property>
    </bean>
    <!--配置login过滤器属性-->
    <bean id="authc" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <!--登录表单中的用户名和密码的name属性必须和此保持一致。其默认为username和password-->
        <property name="usernameParam" value="uname"></property>
        <property name="passwordParam" value="pwd"></property>
        <!--配置renumberMe-->
        <property name="rememberMeParam" value="rm"></property>
    </bean>
    <!--配置会话管理器  在shiro-web jar下-->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!--设置session的超时时间20min-->
        <property name="globalSessionTimeout" value="1200000"></property>
        <!--删除失效session-->
        <property name="deleteInvalidSessions" value="true"></property>
    </bean>
    <!--注册SimpleCookie-->
    <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <!--设置Cookie的名称-->
        <property name="name" value="rm"></property>
        <!--设置cookie的免密时间为7天 单位秒-->
        <property name="maxAge" value="604800"></property>
    </bean>
    <!--注册rememberMeCookie-->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="simpleCookie"></property>
    </bean>
</beans>

[3]自定义Realm
package cn.qt.realm;

import cn.qt.pojo.Admin;
import cn.qt.service.AdminService;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.*;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    AdminService adminService;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname = authenticationToken.getPrincipal().toString();
        Admin admin = adminService.getPwd(uname);
        if (admin!=null){
            //把数据给SimpleAuthenticationInfo,用于认证     uname  pwd  salt realName
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(admin,admin.getPwd(), ByteSource.Util.bytes(admin.getSalt()), "userRealm");
            return  info;
        }

        return null;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin admin = (Admin)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //把角色名称保存到SimpleAuthorizationInfo
        info.addRole(admin.getRole().getRname());
        return info;
    }

}
[4]Controller层的登录函数

把登录和认证的操作全部交给shiro完成
以往都是在登录Controller完成的,即在该函数中获得前端页面传入用户名和密码,再调用函数根据用户名查询用户表。对返回结果进行判断,根据不同的判断结果做出不同的决定(登录成功或者登录失败)。
现该操作交给shiro完成,该函数内容改为:

@RequestMapping("adminlogin")
    public String adminlogin(Admin admin,HttpServletRequest req){
        //查看具体的异常信息,获得异常信息名称
        Object ex = req.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        System.out.println(ex);
        if (UnknownAccountException.class.getName().equals(ex)){
            req.setAttribute("msg","用户名错误");
        }else if(IncorrectCredentialsException.class.getName().equals(ex)){
            req.setAttribute("msg","密码错误");
        }else {
            req.setAttribute("msg","未知异常");
        }
        return "error";
    }

2.SessionManager管理

完成功能:用户超过20min未进行操作后,销毁其session
(1)配置会话管理器

  <!--配置会话管理器  在shiro-web jar下-->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!--设置session的超时时间20min-->
        <property name="globalSessionTimeout" value="1200000"></property>
        <!--删除失效session-->
        <property name="deleteInvalidSessions" value="true"></property>
    </bean>

(2)把配置的会话管理器赋值给securityManager

	<!--  该步骤在applicationContext-shiro.xml中  -->
	<!--C、注册securityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--设置自定义realm-->
        <property name="realms" ref="userRealm"></property>
        <!--设置会话管理器-->
        <property name="sessionManager" ref="sessionManager"></property>
    </bean>

3.实现rememberMe功能

rememberMe作用:用户勾选记住我的复选框登录后关闭网页后,再直接访问登录成功后跳往的页面(一般为主页),访问到的主页是其登录后的页面。
以CSDN为例,登录后不注销直接关闭页面,下次进入CSDN官网时却已经登录了

时长设置为7天
(1)前端页面

	<p>
        记住我:<input type="checkbox" name="rm"/>
    </p>

(2)applicationContext-shiro.xml文件
步骤A:

	<!--注册SimpleCookie-->
    <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <!--设置Cookie的名称  value必须和前端的记住我name属性保持一致-->
        <property name="name" value="rm"></property>
        <!--设置cookie的免密时间为7天 单位秒-->
        <property name="maxAge" value="604800"></property>
    </bean>
    <!--注册rememberMeCookie-->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="simpleCookie"></property>
    </bean>

步骤B:在设置数据链的属性value标签内,添加图中所圈出的内容
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值