技術開発日記

技術やら日々思ったことを綴ってます。

JettyでcookieにSecure属性、HttpOnly属性の設定方法

JettyでJSESSIONIDとかの cookieにSecure属性、HttpOnly属性の設定をする日本語の情報を見かけなかったので、設定方法をまとめてみました。
対象はJetty9.X。

webdefault.xmlで設定する方法

$(jetty.home)/etc/webdefault.xmlにある設定ファイルを修正

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

tomcatとかの場合と設定ファイルが違うだけて、基本的には同じ記述でいける。

jetty-web.xmlで設定する方法

WEB-INF配下にjetty-web.xmlを作って以下の内容を設定する。

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Get name="sessionHandler">
      <Get name="sessionManager">
        <Set name="sessionCookie">JSESSIONID</Set>
        <Set name="sessionPath">/</Set>
        <Set name="secureCookies" type="boolean">true</Set>
        <Set name="httpOnly" type="boolean">true</Set>
      </Get>
    </Get>
</Configure>

web.xmlで設定する方法

アプリのweb.xmlに以下の内容を追加。
アプリ毎に設定できるけど、Servlet 3.0から。

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   metadata-complete="true"
   version="3.0">
 
   <session-config>
      <comment>This is my special cookie configuration</comment>
      <domain>foo.com</domain>
      <http-only>false</http-only>
      <max-age>30000</max-age>
      <path>/my/special/path</path>
      <secure>true</secure>
      <name>FOO_SESSION</name>
   </session-config>
</web-app>

ソースで設定する方法

ServletContextListener をOverrideしてあげる。
これもアプリ毎に設定できるけど、Servlet 3.0から。

import javax.servlet.SessionCookieConfig;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class TestListener implements ServletContextListener {
 
    public void contextInitialized(ServletContextEvent sce) {
        String comment = "This is my special cookie configuration";
        String domain = "foo.com";
        String path = "/my/special/path";
        boolean isSecure = true;
        boolean httpOnly = false;
        int maxAge = 30000;
        String cookieName = "FOO_SESSION";
 
        SessionCookieConfig scf = sce.getServletContext().getSessionCookieConfig();
 
        scf.setComment(comment);
        scf.setDomain(domain);
        scf.setHttpOnly(httpOnly);
        scf.setMaxAge(maxAge);
        scf.setPath(path);
        scf.setSecure(isSecure);
        scf.setName(coookieName);
        }
    }
 
    public void contextDestroyed(ServletContextEvent sce){}
}

まとめ

アプリ毎にcookieの属性を変えたい場合はソースで直接設定してあげたり、web.xmlで設定する必要があるけど、個人的にはservletのバージョンが関係ないのと、複数のアプリが乗っている場合にアプリ毎に設定してあげる必要がないっていう意味ではデフォルトで置いてあるwebdefault.xmlを修正するのが一番楽な気がします。

参考:http://www.eclipse.org/jetty/documentation/current/session-management.html