// 从当前请求中获取SecurityContext,HttpRequestResponseHolder这个类只是简单的对 // HttpServletRequest和HttpServletResponse进行了一层包装 public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequestrequest= requestResponseHolder.getRequest(); HttpServletResponseresponse= requestResponseHolder.getResponse(); HttpSessionhttpSession= request.getSession(false); // 从HttpSession中读取SecurityContext SecurityContextcontext= readSecurityContextFromSession(httpSession); // 如果session中不存在就生成一个空的安全上下文 if (context == null) { if (logger.isDebugEnabled()) { logger.debug("No SecurityContext was available from the HttpSession: " + httpSession + ". " + "A new one will be created."); } context = generateNewContext();
} ...省略部分代码 // 返回安全上下文信息 return context; } // 持久化SecurityContext publicvoidsaveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { SaveContextOnUpdateOrErrorResponseWrapperresponseWrapper= WebUtils .getNativeResponse(response, SaveContextOnUpdateOrErrorResponseWrapper.class); if (responseWrapper == null) { thrownewIllegalStateException( "Cannot invoke saveContext on response " + response + ". You must use the HttpRequestResponseHolder.response after invoking loadContext"); } // saveContext() might already be called by the response wrapper // if something in the chain called sendError() or sendRedirect(). This ensures we // only call it // once per request. if (!responseWrapper.isContextSaved()) { responseWrapper.saveContext(context); } } // 根据SPRING_SECURITY_CONTEXT_KEY从HttpSession获取SecurityContext private SecurityContext readSecurityContextFromSession(HttpSession httpSession) { finalbooleandebug= logger.isDebugEnabled();
if (httpSession == null) { if (debug) { logger.debug("No HttpSession currently exists"); }
if (contextFromSession == null) { if (debug) { logger.debug("HttpSession returned null object for SPRING_SECURITY_CONTEXT"); }
returnnull; }
// We now have the security context object from the session. if (!(contextFromSession instanceof SecurityContext)) { if (logger.isWarnEnabled()) { logger.warn(springSecurityContextKey + " did not contain a SecurityContext but contained: '" + contextFromSession + "'; are you improperly modifying the HttpSession directly " + "(you should always use SecurityContextHolder) or using the HttpSession attribute " + "reserved for this class?"); }
returnnull; }
if (debug) { logger.debug("Obtained a valid SecurityContext from " + springSecurityContextKey + ": '" + contextFromSession + "'"); }
// Everything OK. The only non-null return from this method.