Shiro -- session management

Keywords: Java Session Shiro Apache xml

session management

Shiro provides a complete enterprise level session management function, independent of the underlying container (such as web container tomcat), which can be used in both Java Se and Java EE environments. It provides session management, session event monitoring, session storage / persistence, container independent clustering, expiration / expiration support, transparent support for the web, SSO single sign on support and other features. That is to say, using Shiro's session management directly can directly replace session management such as web container.

Conversation

The so-called session refers to the connection relationship that users maintain when accessing the application. In multiple interactions, the application can identify who the current user is, and can save some data in multiple interactions. For example, after logging in successfully when visiting some websites, the website can remember the user and identify who the current user is before exiting.

Shiro's session support can be used not only in normal Java se applications, but also in Java EE applications, such as web applications. And the usage is consistent.

In Shiro, it can be found that all the user's session information is controlled by Shiro. That is to say, all the processing information related to the user can be obtained through Shiro. In fact, Shiro's session can obtain the value stored in HttpSession, and all the information can be obtained through the Subject interface.

Common API:

      Subject.getSession() ----- Obtain Shiro Of session

        session.setAttribute(key,val) & session.getAttribute(key) & session.removeAttribute(key)

        session.getId() ------  Get session ID

        session.getTimeout() & session.setTimeout(Millisecond) ------- Set up/Get current Session The expiration time of.

        session.getStartTimestamp() & session.getLastAccessTime()  --------  Get the start time and last access time of the session

        session.stop() ------Subject.logout()Automatically called session.stop(). 

 

If you want to perform session management, you must free space regularly, so you need the timing component to complete this.

<dependency>
     <groupId>org.apache.shiro</groupId>
     <artifactId>shiro-quartz</artifactId>
     <version>1.2.2</version>
</dependency>

shiro-single.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <!-- this bean Of id And web.xml in shiro Consistent configuration -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!-- Location of redirection without authentication -->
        <property name="loginUrl" value="/actions/login"/>
        <!-- Where to log in successfully -->
        <property name="successUrl" value="/home.jsp"/>
        <!-- Location without permission to jump -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- Intercept request-->
        <property name="filterChainDefinitions">
            <value>
                <!-- Login request is not blocked -->
                /actions/security/login = anon
                <!-- Visit admin Related requests, require authentication,
                     And through the custom interceptor permissionFilter,Last but not least coder Jurisdiction-->
                /actions/admin/** = authc,permissionFilter,roles[coder]
                /actions/obtainAllUsers = user
                /actions/logout = logout
                /actions/** = authc
            </value>
        </property>
        <!-- User defined filter -->
        <property name="filters">
            <map>
                <entry key="permissionFilter" value-ref="userAccessControlFilter"/>
            </map>
        </property>
    </bean>

    <!-- custom Realm -->
    <bean id="userRealm" class="com.jay.shiro.UserRealm"/>

    <!-- securityManager object-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- Introduce UserRealm -->
        <property name="realm" ref="userRealm"/>
        <!-- Introduce remember me manager-->
        <property name="rememberMeManager" ref="rememberMeManager"/>
        <!-- Introduce sessionManager-->
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!-- Session manager ,Time in milliseconds-->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!--Remove URL Medium JSESSIONID-->
        <property name="sessionIdUrlRewritingEnabled" value="false"/>
        <!-- Session lifetime(Millisecond) -->
        <property name="globalSessionTimeout" value="200000"/><!-- 10 Minute -->
        <!-- Delete invalid session-->
        <property name="deleteInvalidSessions" value="true"/>
        <!-- scanning session thread,Responsible for cleaning up timeout sessions -->
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <!-- Used is QuartZ Components to clean regularly-->
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
        <!-- session Session required cookie Template-->
        <property name="sessionIdCookieEnabled" value="true"/>
        <property name="sessionIdCookie" ref="sessionIdCookie"/>
        <!-- Yes session Implementation class for adding, deleting, modifying and checking -->
        <property name="sessionDAO" ref="sessionDAO"/>
    </bean>

    <!-- Session validation scheduler ,Time in milliseconds-->
    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
        <property name="sessionValidationInterval" value="30000"/>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!-- Conversation ID generator -->
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!-- Session read-write implementation class-->
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>

    <!-- Conversation Cookie Template -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="sid"/>
        <property name="httpOnly" value="true"/>
        <!--maxAge=-1 Indicates that the browser fails to close this Cookie -->
        <property name="maxAge" value="-1"/>
    </bean>
    <!-- rememberMeCookie: Remember me Cookie,Storage time: 30 days -->
    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="2592000"/><!-- 30 day -->
    </bean>

    <!-- rememberMe Manager -->
    <bean id="rememberMeManager"
          class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>

    <!-- Shiro Life cycle processor,,Guarantee realization shiro Internal life cycle function bean Implementation -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

Introducing shiro-single.xml into spring

   <! -- import shiro's configuration file -- >
    <import resource="shiro-single.xml"/>

 

Enter a value when logging in, and get it from the session after logging in

 

 

 

Then click the "enter administrator page" hyperlink to return the relevant request. In the Controller processing this request in the background, use Shiro to get Shiro's session, and try to get the value of the Key value pair whose Key is "abc". Print "def" on the console, indicating that the session session provided by Shiro can get the Key value pair from HttpSession correctly. At the same time, it also proves that the integration Shiro session is successful.

Posted by genics on Sat, 07 Mar 2020 00:46:52 -0800