Post

Local storage, Session Storage, Cookie

๐Ÿ“ฅ Local storage VS Session Storage

๐Ÿ“ซ Local storage

  1. Lifespan: ์˜๊ตฌ์ ์ธ ์ €์žฅ์†Œ
    ์‚ฌ์šฉ์ž๊ฐ€ ์˜๋„์ ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œํ•˜๊ฑฐ๋‚˜ ๋ธŒ๋ผ์šฐ์ € ์บ์‹œ๋ฅผ ์ง€์šฐ์ง€ ์•Š๋Š” ์ด์ƒ ์˜๊ตฌ์ ์œผ๋กœ ๋ณด๊ด€ ๋กœ๊ทธ์•„์›ƒ ํ›„์—๋„ ๋ฐ์ดํ„ฐ ๋‚จ์•„ ์žˆ์Œ
  2. Scope: ๋„๋ฉ”์ธ ๋ณ„๋กœ ์ €์žฅ
    ๋„๋ฉ”์ธ๋ณ„๋กœ ์ €์žฅ๋˜๋ฉฐ, ๋™์ผํ•œ ๋„๋ฉ”์ธ์—์„œ๋งŒ ๋ฐ์ดํ„ฐ ์ ‘๊ทผ ๊ฐ€๋Šฅ
    shared across all tabs/windows from the same orgin(same protocoal, domain, port)
    accessible in another tab/window from the same orgin
    v
  3. Storage Limit: ์šฉ๋Ÿ‰
    ๋Œ€๋ถ€๋ถ„ ๋ธŒ๋ผ์šฐ์ € Local storage ์šฉ๋Ÿ‰์€ 5~10MB

๐Ÿ“ญ Session Storage

  1. Lifespan: ์ผ์‹œ์ ์ธ ์ €์žฅ์†Œ
    ๋ธŒ๋ผ์šฐ์ €์˜ ํƒญ, ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ์ž๋™์œผ๋กœ ๋ฐ์ดํ„ฐ ์‚ญ์ œ
    ์ผ์‹œ์ ์ธ ๋ฐ์ดํ„ฐ ์ €์žฅ์— ์ ํ•ฉ
  2. Scope: ํƒญ๋ณ„๋กœ ์ €์žฅ, page session
    ๊ฐ ๋ธŒ๋ผ์šฐ์ € ํƒญ๋ณ„๋กœ ์ €์žฅ
    each brower tab or window has its own session storage and is not accessible in another tab/window
  3. Storage Limit: ์šฉ๋Ÿ‰
    ๋Œ€๋ถ€๋ถ„ ๋ธŒ๋ผ์šฐ์ € Session storage ์šฉ๋Ÿ‰ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ 5~10MB

1๏ธโƒฃ ์„œ๋ฒ„์—์„œ ์ฟ ํ‚ค ์„ค์ •

์„œ๋ฒ„์—์„œ ์‚ฌ์šฉ์ž๊ฐ€ ์ธ์ฆ์ด ๋˜๋ฉด, JWT ํ† ํฐ์„ ์ƒ์„ฑํ•˜๊ณ  ์ด๋ฅผ ์ฟ ํ‚ค์— ์ €์žฅ
token = jwt.encode({"user_id": user_id}, SECRET_KEY, algorithm="SH256")
์ฟ ํ‚ค๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ HTTP ์‘๋‹ต ํ—ค๋”์— Set-Cookie๋ฅผ ์„ค์ •ํ•˜์—ฌ ํ† ํฐ์„ ์ „๋‹ฌ
response.set_cookie()
response.set_cookie(key="access_token", value=token) <br>

2๏ธโƒฃ ํด๋ผ์ด์–ธํŠธ์—์„œ ์ฟ ํ‚ค ์‚ฌ์šฉ

ํด๋ผ์ด์–ธํŠธ์—์„œ๋Š” ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ† ํฐ์„ ์ €์žฅ
์ฟ ํ‚ค๋Š” ๋ธŒ๋ผ์šฐ์ €์— ์˜ํ•ด ์ž๋™์œผ๋กœ ์ €์žฅ
์„œ๋ฒ„๋กœ ์š”์ฒญ์„ ๋ณด๋‚ผ ๋•Œ๋งˆ๋‹ค ์ฟ ํ‚ค๊ฐ€ ์ž๋™์œผ๋กœ ํฌํ•จ

3๏ธโƒฃ ์„œ๋ฒ„์—์„œ ์ฟ ํ‚ค ์ฝ๊ธฐ

์„œ๋ฒ„์—์„œ๋Š” ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ ์š”์ฒญ์˜ ์ฟ ํ‚ค๋ฅผ ํ™•์ธํ•˜์—ฌ JWT ํ† ํฐ์„ ์ถ”์ถœํ•˜๊ณ  ์ธ์ฆ
Request
async def get_token(request: Request): return request.cookies.get("access_token")

๐Ÿ’ก ์ฃผ์˜!

๋‹จ, ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ HttpOnly์™€ Secure ํ”Œ๋ž˜๊ทธ๋ฅผ ์„ค์ •ํ•˜์—ฌ ์ฟ ํ‚ค์˜ ๋ณด์•ˆ์„ ๊ฐ•ํ™”ํ•ด์•ผ ํ•œ๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from fastapi import FastAPI, Response, Request, Depends
import jwt

app = FastAPI()

@app.post("/login")
async def login(response: Response):
    # ์‚ฌ์šฉ์ž ์ธ์ฆ ๋กœ์ง
    # ...

    # JWT ํ† ํฐ ์ƒ์„ฑ
    token = jwt.encode({"user_id": user_id}, SECRET_KEY, algorithm="SH256")

    # ์‘๋‹ต ํ—ค๋”์— ์ฟ ํ‚ค ์„ค์ •
    response.set_cookie(key="access_token", value=token)
    return {"message": "๋กœ๊ทธ์ธ ์„ฑ๊ณต"}

async def get_token(request: Request):
    return request.cookies.get("access_token")

@app.get("/protected")
async def protected_route(token: str = Depends(get_token)):
    # ํ† ํฐ ๊ฒ€์ฆ ๋ฐ ์ธ์ฆ ๋กœ์ง
    # ...

This post is licensed under CC BY 4.0 by the author.