首页 Java java教程 关于shiro的源码学习之Session session = getSession()的实例分析

关于shiro的源码学习之Session session = getSession()的实例分析

Jul 24, 2017 pm 01:26 PM
session shiro

subject代表用户访问服务器的一些操作:比做登录、登出,查看角色/权限、

同时可获取session如:subject.getSession(),该接品,如果之前不存在session,则创建session。创建过程大致为:

subject委托SecurityManager创建、SecurityManager委托SessionManager创建,SessionManager通过SessionFactory工厂创建。由此可见,shiro创建的过程分工明确。

创建过程分析如下。

(1)在DelegatingSubject类中可以获取Session:

public Session getSession(boolean create) {
      .......
      SessionContext sessionContext = createSessionContext();
      //创建Session上下文,context有个backMap,存放创建Session时所需的数据
      Session session = this.securityManager.start(sessionContext);
      this.session = decorate(session);//创建代理session,当session.stop()调用时,清空subject的session
      .......
      return this.session;//返回代理session
 }
登录后复制

(2)SecurityManager委托sessionManager(DefaultSessionManage)处理Session的创建:

1 public Session start(SessionContext context) throws AuthorizationException {
2     return this.sessionManager.start(context);
3     }
登录后复制

*注意:DefaultSessionManage的内部架构为:

(3)AbstractNativeSessionManager创建Session并管理Session:

public Session start(SessionContext context) {
        Session session = createSession(context);//通过模板模式,子类实现通过上下仍创建Session
        applyGlobalSessionTimeout(session);//更新sessionDAO的sessions(map<String,session>)
        onStart(session, context);//一个槽点,待子类实现
        notifyStart(session);//注册的监听器开始执行
        //Don&#39;t expose the EIS-tier Session object to the client-tier:
        return createExposedSession(session, context);//创建暴露的Session
    }
登录后复制

(4)到此Session的创建完成,及细节代码如下:AbstractNativeSessionManager交给AbstractValidatingSessionManager处理:

protected Session createSession(SessionContext context) throws AuthorizationException {
        enableSessionValidationIfNecessary();
        //创建Session之前,先起一个Session自动定时任务的线程去执行,校验sessionDAO的sessions是否过期。
        return doCreateSession(context);
    }
//
private void enableSessionValidationIfNecessary() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (isSessionValidationSchedulerEnabled() && (scheduler == null || !scheduler.isEnabled())) {
            enableSessionValidation();
        }
    }
//
protected void enableSessionValidation() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (scheduler == null) {
            scheduler = createSessionValidationScheduler();
            //scheduler = new ExecutorServiceSessionValidationScheduler(this);scheduler.setInterval(getSessionValidationInterval());
            setSessionValidationScheduler(scheduler);
        }
        if (log.isInfoEnabled()) {
            log.info("Enabling session validation scheduler...");
        }
        scheduler.enableSessionValidation();//自动任务启动执行
        afterSessionValidationEnabled();//一个槽点,待子类实现
}
登录后复制

(5)ExecutorServiceSessionValidationScheduler验证Session的过期:

/**
     * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals 
     * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
     */
    //TODO Implement an integration test to test for jvm exit as part of the standalone example
    // (so we don&#39;t have to change the unit test execution model for the core module)
    public void enableSessionValidation() {
        if (this.interval > 0l) {
            this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {  
            public Thread newThread(Runnable r) {  
                Thread thread = new Thread(r);  
                thread.setDaemon(true);  
                return thread;  
                }  
            });                  
            this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
            this.enabled = true;
        }
    }

    public void run() {
        if (log.isDebugEnabled()) {
            log.debug("Executing session validation...");
        }
        long startTime = System.currentTimeMillis();
        this.sessionManager.validateSessions();//ExecutorServiceSessionValidationSchedule的在被SessionManager创建里,
        long stopTime = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
        }
    }
登录后复制

(6)AbstractValidatingSessionManager验证Session的过期:

/**
     * @see ValidatingSessionManager#validateSessions()
     */
    public void validateSessions() {
        if (log.isInfoEnabled()) {
            log.info("Validating all active sessions...");
        }
        int invalidCount = 0;
        Collection<Session> activeSessions = getActiveSessions();//获取取保存的Session
        if (activeSessions != null && !activeSessions.isEmpty()) {
            for (Session s : activeSessions) {
                try {
                    //simulate a lookup key to satisfy the method signature.
                    //this could probably stand to be cleaned up in future versions:
                    SessionKey key = new DefaultSessionKey(s.getId());
                    validate(s, key);
                } catch (InvalidSessionException e) {
                    if (log.isDebugEnabled()) {
                        boolean expired = (e instanceof ExpiredSessionException);
                        String msg = "Invalidated session with id [" + s.getId() + "]" +
                                (expired ? " (expired)" : " (stopped)");
                        log.debug(msg);
                    }
                    invalidCount++;
                }
            }
        }

        if (log.isInfoEnabled()) {
            String msg = "Finished session validation.";
            if (invalidCount > 0) {
                msg += "  [" + invalidCount + "] sessions were stopped.";
            } else {
                msg += "  No sessions were stopped.";
            }
            log.info(msg);
        }
    }
    //类DefaultSessionManager实现getActiveSessions接口
    protected abstract Collection<Session> getActiveSessions();

     protected Collection<Session> getActiveSessions() {
        Collection<Session> active = sessionDAO.getActiveSessions();
        return active != null ? active : Collections.<Session>emptySet();
    }
登录后复制

(7)Session的校验完成,接下来是DefaultSessionManager进行Session的创建:

protected Session doCreateSession(SessionContext context) {
        Session s = newSessionInstance(context);
        if (log.isTraceEnabled()) {
            log.trace("Creating session for host {}", s.getHost());
         }
        create(s);
        return s;
     }

   protected Session newSessionInstance(SessionContext context) {
      return getSessionFactory().createSession(context);
   }
   protected void create(Session session) {
      if (log.isDebugEnabled()) {
         log.debug("Creating new EIS record for new session instance [" + session + "]");
        }
      sessionDAO.create(session);
    }
登录后复制

(8)DefaultSessionManager委托Session(MemorySessionDAO)维护Session:

protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        storeSession(sessionId, session);
        return sessionId;
    }
        protected Session storeSession(Serializable id, Session session) {
          if (id == null) {
             throw new NullPointerException("id argument cannot be null.");
          }
          return sessions.putIfAbsent(id, session);
        }
登录后复制

(9) 创建并维护Session之后,AbstractNativeSessionManager交给注册好的监听器,监听器调用启动onStart接口

  protected void notifyStart(Session session) {
  2         for (SessionListener listener : this.listeners) {
  3             listener.onStart(session);
  4         }
  5     }
登录后复制

(10)最后创建委托Session,

protected Session createExposedSession(Session session, SessionContext context) {        
return new DelegatingSession(this, new DefaultSessionKey(session.getId()));
    }
登录后复制

(11)最后Subject创建自己的代理Session,主要用来拦截stop方法:

protected Session decorate(Session session) {
         if (session == null) {
             throw new IllegalArgumentException("session cannot be null");
         }
         return new StoppingAwareProxiedSession(session, this);
     }
    private class StoppingAwareProxiedSession extends ProxiedSession {

           private final DelegatingSubject owner;

           private StoppingAwareProxiedSession(Session target, DelegatingSubject owningSubject) {
                super(target);
                owner = owningSubject;
            }
16            public void stop() throws InvalidSessionException {
           super.stop();
           owner.sessionStopped();
         }
       }
登录后复制

总结:Session(SimpleSession)在DefaultSessionManage中创建时,被封装在DelegatingSession中,在subject中又被装饰为代理session(StoppingAwareProxiedSession),原始的数据很好的保存,使的客户端不可随意修改原始的Session

........


以上是关于shiro的源码学习之Session session = getSession()的实例分析的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1671
14
CakePHP 教程
1428
52
Laravel 教程
1331
25
PHP教程
1276
29
C# 教程
1256
24
php session刷新后没有了怎么办 php session刷新后没有了怎么办 Jan 18, 2023 pm 01:39 PM

php session刷新后没有了的解决办法:1、通过“session_start();”开启session;2、把所有的公共配置写在一个php文件内;3、变量名不能和数组下标相同;4、在phpinfo里面查看session数据的存储路径,并查看该文件目录下的sessio是否保存成功即可。

SpringBoot Session怎么设置会话超时 SpringBoot Session怎么设置会话超时 May 15, 2023 pm 02:37 PM

问题发现springboot项目生产session-out超时问题,描述下问题:在测试环境通过改动application.yaml配置session-out,经过设置不同时间验证session-out配置生效,于是就直接设置了过期时间为8小时发布到了生产环境。然而中午接到客户反应项目过期时间设置较短,半小时不操作就会话过期需要反复登陆。解决处理开发环境:springboot项目内置Tomcat,所以项目中application.yaml配置session-out是生效的。生产环境:生产环境发布是

session失效怎么解决 session失效怎么解决 Oct 18, 2023 pm 05:19 PM

session失效通常是由于 session 的生存时间过期或者服务器关闭导致的。其解决办法:1、延长session的生存时间;2、使用持久化存储;3、使用cookie;4、异步更新session;5、使用会话管理中间件。

Springboot2 session设置超时时间无效怎么解决 Springboot2 session设置超时时间无效怎么解决 May 22, 2023 pm 01:49 PM

问题:今天项目中遇到了一个设置时间超时的问题,按SpringBoot2的application.properties更改一直不生效。解决方案:server.*属性用于控制SpringBoot使用的嵌入式容器。SpringBoot将使用ServletWebServerFactory实例之一创建servlet容器的实例。这些类使用server.*属性来配置受控的servlet容器(tomcat,jetty等)。当应用程序作为war文件部署到Tomcat实例时,server.*属性不适用。它们不适用,

PHP Session 跨域问题的解决方法 PHP Session 跨域问题的解决方法 Oct 12, 2023 pm 03:00 PM

PHPSession跨域问题的解决方法在前后端分离的开发中,跨域请求已成为常态。在处理跨域问题时,我们通常会涉及到session的使用和管理。然而,由于浏览器的同源策略限制,跨域情况下默认情况下无法共享session。为了解决这个问题,我们需要采用一些技巧和方法来实现session的跨域共享。一、使用cookie跨域共享session最常

session php默认失效时间是多少 session php默认失效时间是多少 Nov 01, 2022 am 09:14 AM

session php默认失效时间是1440秒,也就是24分钟,表示客户端超过24分钟没有刷新,当前session就会失效;如果用户关闭了浏览器,会话就会结束,Session就不存在了。

Redis的共享session应用如何实现短信登录 Redis的共享session应用如何实现短信登录 Jun 03, 2023 pm 03:11 PM

1.基于session实现短信登录1.1短信登录流程图1.2实现发送短信验证码前端请求说明:说明请求方式POST请求路径/user/code请求参数phone(电话号码)返回值无后端接口实现:@Slf4j@ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1.校验手机号if

Java shiro安全框架如何使用 Java shiro安全框架如何使用 May 03, 2023 am 11:22 AM

1.shiro安全框架ApacheShiro是一个强大易用的Java安全框架,提供了认证、授权、加密和session会话管理等功能,对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架springsecurity,Shiro要简单的多。Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架。Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaS

See all articles