java - Tomcat 7.1 为来自同一客户端的每个请求创建新 session

标签 java tomcat7 sessionid

我正在使用 Tomcat 7 并尝试将一些对象存储到 session 中,但每当同一客户端发出新请求时,Tomcat 就会创建一个新 session 。

以下是我的代码,它基本上是一个过滤器,它调用另一个应用程序来执行身份验证和授权并返回一个对象。我使用 Apache httpclient 进行此通信

过滤器类

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  throws IOException, ServletException {

    // If the request is for any static contents do not invoke this filter
    if (!isWorthyRequest((HttpServletRequest)request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpClient httpClient = null;
    try {
        if (validateApp && request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest)request;
            HttpSession httpSession = httpServletRequest.getSession(false);
            if (null != httpSession && null != httpSession.getAttribute("userInfoMap")) {
                LOG.info(" User is already Authenticated :: session Id :: "+httpSession.getId()
                        +" Created At :: "+ new Date(httpSession.getCreationTime())
                +" Last Accessed At :: "+new Date(httpSession.getLastAccessedTime()));
                // The user is already Authenticated & Authorize just pass the request to next chain
            } else {
                LOG.info("Calling Authenication / Authorization Module :: URL "+securityServiceURL);
                // Calling Authentication and Authorization
                httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(securityServiceURL);
                // Getting the SM Header
                httpPost.setHeader(IaasConstants.SM_USER, httpServletRequest.getHeader(IaasConstants.SM_USER));
                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                // urlParameters.add(new BasicNameValuePair(IaasConstants.SOURCE_APP_NAME, "vElite"));
                urlParameters.add(new BasicNameValuePair(IaasConstants.SUB_SERVICE_NAME, IaasConstants.SERVICE_AUTHENTICATE_USER));
                httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                String jsonString = null; 
                if (null != httpEntity) {
                    jsonString = EntityUtils.toString(httpEntity);
                }
                HttpServletResponse httpServletResponse = (HttpServletResponse)response;
                // User is a valid user
                if (httpResponse.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                    LOG.info(" User is valid :: user :: "+httpServletRequest.getHeader(IaasConstants.SM_USER)+" jsonObject :: "+jsonString);
                    if (null != jsonString) {
                        Gson gSon = new Gson();
                        Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
                        Map<String, Object> userInfoMap = gSon.fromJson(jsonString, mapType);
                        httpSession = httpServletRequest.getSession(false);
                        if (null == httpSession) {
                            LOG.info("Session Created and the userInfoMap is stored inside session :: ");
                            httpSession = httpServletRequest.getSession(true);
                            httpSession.setAttribute(IaasConstants.USER_INFO_MAP, userInfoMap);
                        } else {
                            httpSession.setAttribute(IaasConstants.USER_INFO_MAP, userInfoMap);
                        }
                    }
                } else {
                    // Bad User
                    LOG.info("Invalid User ::: with status code :: "
                    +httpResponse.getStatusLine().getStatusCode()
                    +" Status Message :: "+httpResponse.getStatusLine().getReasonPhrase());

                    httpServletResponse.setStatus(httpResponse.getStatusLine().getStatusCode());
                    httpServletResponse.sendError(httpResponse.getStatusLine().getStatusCode());
                    httpServletResponse.flushBuffer();
                    return;
                }
            }

        }
        HttpServletResponseCopier responseCopier = new HttpServletResponseCopier((HttpServletResponse) response);
        // pass the request along the filter chain
        chain.doFilter(request, responseCopier);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (null != httpClient) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

/**
 * @see Filter#init(FilterConfig)
 */
public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
    this.fConfig = fConfig;
    validateApp = Boolean.valueOf(fConfig.getInitParameter(IaasConstants.VALIDATE_APP));
    securityServiceURL = fConfig.getInitParameter(IaasConstants.SECURITY_SERVICE_URL);
}

   private boolean isWorthyRequest(HttpServletRequest request) {
       String url = request.getRequestURI().toString();
       Matcher m = excludeUrls.matcher(url);

       return (!m.matches());
   }

Web.xml

<session-config>
<session-timeout>15</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>

如何才能让 Tomcat 维护来自同一客户端的请求的 session ?

我尝试了以下选项,但对我不起作用。

  1. 在全局 context.xml 中添加 Valve,例如 <Valve className="org.apache.catalina.authenticator.BasicAuthenticator" changeSessionIdOnAuthentication="false"/>

  2. 删除<http-only>true</http-only> web.xml 中的选项

据我了解,由于 session 固定保护问题,Tomcat 为每个请求创建新的 session ID,但是还有其他替代方法来维护 session 吗?

最佳答案

<secure>true</secure>意味着 cookie 应该在 HTTPS 连接中设置,我想您正在创建 HTTP,所以将其删除

关于java - Tomcat 7.1 为来自同一客户端的每个请求创建新 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19436360/

相关文章:

java - 在 appium studio 上找到的元素不适用于 appium 独立服务器,反之亦然

PHP session ID 相同但变量丢失

java - 有没有办法从 EJB 模块访问 HttpSession?

node.js - express-session - session id 和 connect.sid 之间的区别?

java - Hibernate QueryTranslatorImpl HQL AST解析性能

java - 什么是NullPointerException,我该如何解决?

java - 从另一个插件访问内置的 intellij 插件

java - 在 apache tomcat 中部署除 webapp 文件夹以外的 Web 应用程序

tomcat - 如何在tomcat中启用热部署

jms - 使用 bitronix 阻塞线程