3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

今さらcookieについてまとめる

Last updated at Posted at 2022-11-22

背景

Cookieとは

MDN Web Docs: HTTP Cookie の使用

cookieを3つのパターンに分けて触ってみる

  • 1st Party HTTP Cookie
    • 1st ドメインのサーバーからSet-Cookieレスポンスヘッダによって設定されるCookie
  • 3rd Party Cookie
    • 3rd ドメインのサーバーからSet-Cookieレスポンスヘッダによって設定されるCookie
  • JS Cookie
    • Javascriptの document.cookie で設定されるCookie

環境

  • MacOS Monterey: 12.6
  • Chrome: 107.0.5304.110
  • Safari: 16.0

1st Party HTTP Cookie

WebページをホストしているドメインのサーバーからSet-Cookieレスポンスヘッダによって設定されるCookie

特徴

  • 保持期間が長い
  • HTTPOnlyがTrueになり、JSの document.cookie で参照したり更新したりできない

設定方法

from flask import Flask, jsonify, make_response

app = Flask(__name__)

@app.route("/cookie_test")
def cookie_test():
    resp = make_response()
    max_age = 60 * 60 * 24 * 120  # 120 days
    # domain="xxxx" でdomain指定できるが、配信元以外のドメインを指定しするとcookie setされなかった
    # domainを指定しないと自動的に配信元のdomainが指定される
    resp.set_cookie('uid', value="asdf", max_age=max_age, path='/', secure=True, httponly=True)
    return resp

3rd Party Cookie

Webページをホストしているドメイン以外のサーバーからSet-Cookieレスポンスヘッダによって設定されるCookie

特徴

  • safari も chromeも登録できなかった

JS Cookie

Webページをホストしているドメインのサーバーから配信されるJavaScriptの domument.cookie = で設定されるcookie. 配信元が1stドメインだろうが3rdドメインだろうが挙動は変わらない

特徴

  • 保持期間が1st Party Http Cookieに比べて短い
    • chromeでは1年くらいいけた
    • safariでは7日

設定方法

function writeToCookie() {
    max_age = 60 * 60 * 24 * 1000
    document.cookie = "1st_with_write_domain=uuuu;domain=test.com;max-age=" + max_age;
}

writeToCookie()

参考

3
3
0

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
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?