LoginSignup
4

More than 3 years have passed since last update.

posted at

updated at

JavaでCookieにSameSite属性をつける

(20/01/08 19:45追記)

概要

javax.servlet.http.CookieにはSameSite属性を付与するAPIがありません。
そんな時の対応です。
ちなみにSameSite属性はほぼ全てのブラウザが対応しています。
参考

Cookieクラスを使用せず、Set-Cookieヘッダーを使用する

Spring bootでやってみます。

@RestController
public class DemoController {

    @GetMapping(value = "/")
    public String index(HttpServletResponse response) {

        String name = "name";
        String value = "takeshi";

        String cookie = String.format("%s=%s; max-age=3600; Path=/; HttpOnly; Secure; SameSite=Lax;", name, value);

        response.addHeader("Set-Cookie", cookie);

        return "hello, world!";
    }

Screen Shot 2019-08-06 at 17.11.55.png

無事takeshiが入りました。

Spring Boot編

Spring BootにはResponseCookieというヘッダー用のCookie文字列を作ってくれるクラスがあります。
このクラスを使用して、Set-Cookieでセットしたレスポンスを返却すると、Cookieをセットしてくれます。

@RestController
public class DemoController {
    @GetMapping(value = "/")
    public String index(HttpServletRequest request, HttpServletResponse response) {

        String name = "name";
        String value = "takeshi";

        ResponseCookie cookie = ResponseCookie.from(name, value).domain("localhost").maxAge(Duration.ofDays((long) 1))
            .httpOnly(true).secure(true).sameSite("Strict").build();
        response.addHeader("Set-Cookie", cookie.toString());

        return "Hello, World";
    }
}

無題.png

頻繁にCookie書き込みを行う場合は、パラメータで受け取ってセットするカスタムクラスを作った方が良さそうですね。
もしくはApacheやnginxなどのWebサーバ側で一括設定もできます。
参考

参考

Class Cookie
https://stackoverflow.com/questions/42717210/samesite-cookie-in-java-application
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

Class ResponseCookie

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
4