쿠키, 세션, 토큰, 캐시, 웹스토리지 탐구

강연주·2024년 11월 4일

📚 TIL

목록 보기
83/186

유튜브 영상들을 정말 조금 봤다.
쿠키는 데이터가 들어있는 소듕한 그릇같은 것이고
브라우저와 서버가 주거니 받거니 한다.

그런데 그 안에 이제 보통의 민감한 (개인)정보는 세션ID의 모습으로, 구체적인 내용 없이 이동되고, 서버에서 세션ID를 보고 개인을 식별하는 거지.
서버측에서 관리하는 울랄라세션..?

토큰은 막 d348FRss11dGb77nsfpi2838f8g8g8wif
이렇게 이상하게 생긴 긴 문자열...인 거밖에 기억이 안 나네?

저렇게 무언가를 계속 주고받고 하는 일련의 과정이
서버 과부하를 유발할 수 있으므로 '저장소'가 필요한 것인데,
내 브라우저에 저장시키고, 창을 닫아도 가지고 있으려면 로컬스토리지를 사용한다.
세션 스토리지도 있는데요. 조금 더 알아봐야겠군요^ㅇ^...


🧸 브라우저 저장소

https://www.youtube.com/watch?v=5s--sLWzuZc

서버-클라이언트 소통 시의 규약 : HTTP
HTTP는 클라이언트가 서버에게 요청을 보내고 서버는 응답을 보내 접속을 종료
통신이 끝나면 인증에 쓰이는 상태를 유지하지 않는다는 특징
계속해서 통신 연결을 하지 않기 떄문에 자원 절약은 되지만
통신을 할 때마다 새로 연결이 필요해서 클라이언트는 매번 인증을 해야한다는 단점이있다.
➡️ 웹사이트에서 로그인을 했는데도 페이지 이동할 때마다 또 로그인을 해야 하게 됨

로그인한 정보를 어딘가에 저장해서 문제를 해결하는데,
이때 사용하는 것이 브라우저의 스토리지고, 말 그대로 저장소를 뜻한다.
브라우저의 저장공간인 셈이다.

그리고 브라우저 저장소에는, 쿠키 그리고 HTML5부터 제공하는 웹스토리지가 있다.

개발자도구 - Application - Storage - Local Storage, Sesstion Storage, Cookies

셋 다 모두 해당 도메인에 대한 데이터를 브라우저에 저장한다.

쿠키는 서버가 클라이언트에게 전송하는 작은 데이터 파일.
이름, 값, 도메인 정보, 경로 정보, 만료 일자와 시간 등을 담는다.
모든 브라우저에서 지원되지만
메번 서버에 전송이 되고 저장 용량이 작고 보안에 취약한 것이 단점.
다시 보지 않기 팝업 창

HTML5부터, 쿠키의 단점을 보완해 등장한 웹스토리지를 주로 사용.
쿠키와 기능은 유사하지만, 클라이언트에 저장만 할 뿐 서버에 전송하지 않는다.
key와 value의 형태로 데이터 저장.

지속성에 따라 로컬 스토리지와 세션 스토리지로 구분.

  • 로컬 : 브라우저에 반영구 저장, 브라우저 종료해도 데이터 유지
    자동로그인 기능

  • 세션 : 탭, 윈도우 단위로 저장. 탭, 윈도우를 닫을 때 데이터 삭제
    입력 폼 정보, 비로그인 장바구니 기능

https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage
https://developer.mozilla.org/ko/docs/Web/API/Window/sessionStorage


🚥 쿠키, 세션, 캐시가 뭔가요?

https://www.youtube.com/watch?v=OpoVuwxGRDI

각종 편의, 오락시설을 갖춘 대규모 찜질방 울랄라 스파가 있다.
이 스파는 회원 등록 후 입장해서 내부 시설을 마음껏 이용한 뒤 나올 때 한꺼번에 계산하는 방식.
유저가 웹사이트를 이용하는 것을, 울랄라 스파 이용해 비유해본다.

여기서는 쿠폰북이 아닌 '쿠키북'이라는 수첩을 들고 다니면서
이용시설마다 이걸 보여준다.
'쿠키북'에는 시설 측 혹은 내가 직업 뭔가를 기록할 수 있고,
수정하거나 찢어서 버릴 수도 있다.

카페 이용 후 스탬프 받기, 샵에서 맘에 드는 물건 적어 두기, 이벤트를 한 번 안내받았으면 이미 받았다는 사실을 기록해 여러 번 귀찮게 하지 않게 하기 등
쿠키북의 핵심은 1. 내가 들고 다닌다 2. 시설 이용 시마다 보여준다는 점이다.

쿠키는 사이트를 방문하고 이용할 때 브라우저에 저장되는 내용들.
브라우저는 내 컴퓨터에 있으니까 내가 가지고 있는 정보.

그런데 쿠키북에는 한계가 있는데,
내가 임의로 지우거나 고칠 수 있고 심지어 타인이 훔쳐보거나 도둑질하기도 쉽다.
나로서는 민감하거나 중요한 정보를 쿠키북에 적어서 다니기는 불안하고,
울랄라 스파 측에서도 이 손님이 음식을 시켜먹었으니까 나갈 때 지불해야 하는 금액을 쿠키북에 적어주려고 하지는 않을 것이다. 비싼 거 사먹고 내역을 찢어내 버려서 결제를 안 할 수도 있기 때문.
나, 손님이 들고 다니는 쿠키북이 아니라, 스파 측에서 보관하고 관리해야 하는 정보들이 존재한다.

스파 이용객들의 중요 정보를 총괄하는 곳으로 울랄라 세션이 있다.

내가 스파에 입장하면, 울랄라 세션에서 그때 그때 생성되는 바코드를 쿠키북에 하나 찍어준다. 내가 스파를 돌아다니며 시설들을 이용할 때, 이 고객은 회원으로 확인되어입장한 상태다, 어디서 어떤 서비스를 이용했다, 귀중품이 어디에 보관되어 있다 등 쿠키북에 저장하기 곤란한 정보를 울라라 세션에서 관리하고, 그 정보들이 각각 누구의 것인지는 바코드로 구별하는 것이다.

세션에 사용하는 사이트에 접속하면, 서버에서는 사용자를 구별하기 위한 기한이 짧은 임시 키 하나를 브라우저로 보내서 쿠키에 저장한다. '얄코'라는 사용자가 사이트 안의 페이지들을 돌아다닐 때 얄코 님의 중요한 정보들은 이 서버의 메모리나 데이터베이스에 저장된다. 브라우저에 이 사이트의 페이지들에 접속할 때마다, http 요청에 이 키가 담긴 쿠키를 실어서 전송하고, 서버는 그 키를 보고 '아 얘는 얄코 님이구나'하고 인식해서, 얄코의 정보들을 가공해 응답으로 보내주는 것.

네이버에 한 번 로그인한 다음, 네이버의 다른 페이지들을 이용할 때마다 새로 로그인할 필요가 없는 건 쿠키와 세션의 조합으로, 내 컴퓨터에서 네이버에 로그인되어 있다는 것을 네이버 서버가 인지하고 있기 때문이다. 네이버에 속한 모든 쿠키를 지우고 새로고침하면 로그인이 해제되어있다. 서버에서는 세션에 내 로그인 정보를 가지고 있지만, 그것이 내 것임을 증명할 세션 아이디가 내 쿠키 보관함에서 지워졌기 때문이다.

쿠키는 로그인창의 아이디를 자동 완성하거나, 공지 메시지를 하루 안 보기 하거나, 쇼핑몰 사이트에서 비로그인인 채로 장바구니에 물건을 담는 기능 등,
사용자의 편의를 위하지만 지워지거나 조작되거나 가로채이더라도 큰 일은 없을 수준의 정보들을 브라우저에 저장하는 용도로 사용된다.

그리고 사용자나 타인에게 노출되어서는 안 되는, 서비스 제공자가 직접 관리해야 하는 내용들은 세션으로 서버 안에서 다뤄진다.

개발자가 웹사이트를 만들 때, 이 정보를 쿠키에 저장할지 세션에 저장할지 적절한 판단을 내릴 수 있어야 한다. 쿠키로 노출시켜서는 안 될 정보들이 있지만 그렇다고 세션을 남발하면 접속자가 많을 때 서버에 부하가 걸린다.

문어발 기업 울랄라는 신발 판매 사업에도 진출하는데...
울랄라 스파 섹션에 OK마트를 개점한다.
손님이 OK마트에 방문해 신발을 고르는데, 운동화 하나가 맘에 들어 맞는 사이즈로 착화를 요청. 직원은 창고에서 신발을 가져다주고, 손님은 한 번 신어본 뒤 "좀 더 둘러볼게요"하고 간다. 직원이 상황을 보니, 손님이 다시 와서 그 제품을 사거나 다른 제품이랑 비교하면서 다시 신어볼 것 같다. 다시 창고에 갖다놨다가 다시 가져오려면 손님도 직원도 시간과 에너지 낭비이므로, OK매장 한 켠의 큰 백에 일단 넣어 놓는다.
이 백의 이름이 'Ok Cache 백'.

캐시란 개념은 웹뿐만 아니라, 컴퓨터의 메모리 부분이나 안드로이드 등 다양한 곳에서 쓰임. 대부분 공통 의미로, 가져오는 데에 비용이 드는 데이터를 한 번 가져온 후에는 임시로 저장해두는 것이다. 웹 캐시는 이미지 등의 정보를 불러올 때 데이터 사용량도 발생하고 시간도 소모되기 때문에 사용자가 여러 번 방문할 법한 사이트에서는, 한 번 받아온 데이터를 사용자의 컴퓨터 또는 중간 역할을 하는 서버에 저장해둔다.

댓글)
1. 쿠키

  • 쿠키는 클라이언트 측에 저장된 키와 함께 들어있는 작은 파일입니다.
  • 클라이언트의 상태정보를 로컬에 저장합니다.
  • 그래서, 장바구니 기능, '오늘 더이상 창을 보지않음 창 팝업' 등에 사용됩니다.
    1) 클라이언트가 페이지를 요청하면
    2) 서버에서 쿠키를 생성해, http 헤더에 쿠키를 포함시켜 응답합니다
    3) 클라이언트는 이 쿠키를 로컬 pc에서 갖고 있다가, 다시 서버에 요청할 때 HTTP 헤더에 이 쿠키를 함께 전송합니다.
    4) 서버에서는 이 쿠키를 읽어 이전 상태정보를 변경할 필요가 있으면 쿠키를 업데이트해 HTTP 헤더에 변경된 쿠키를 넣어 반환합니다.
  1. 세션
  • 세션은 사용자 정보를 서버측에서 관리합니다.
  • 즉, 보안성이 좋아 로그인같은 보안중요작업에 사용됩니다.
  • 서버는 클라이언트 구분을 위해 세션 ID라는 것을 부여합니다. 웹 브라우저가 서버에 접속하고, 브라우저를 종료할 때 까지 인증상태를 유지합니다.
    1) 클라이언트가 페이지를 요청하면
    2) 서버는 접근한 클라이언트의 request-header필드의 쿠키를 확인해 클라이언트가 세션id를 보냈는지 확인합니다.
    3) 만약 세션id가 존재하지 않으면 서버는 세션id를 생성해 클라이언트에 함께 돌려줍니다.
    이 때, 서버측에서는 세션 저장소에 해당 id를 저장해, 차후 구분할 수 있도록 합니다.
    4) 클라이언트는 세션id를 받으면, 이걸 쿠키를 사용해 저장하고 가지고 있습니다.
    5) 클라이언트는 이제 같은 요청으로 서버에 접속할 때, HTTP요청에 이 세션ID를 같이 서버에 전달해 요청합니다.
    6) 서버는 세션 ID를 전달 받고, 세션저장소에서 해당 세션 ID값을 찾아 클라이언트 정보를 가져와서 클라이언트를 구분합니다. 그리고 요구에 맞는 서비스를 제공합니다.
  1. 차이
  • 데이터 저장위치는 쿠키는 브라우저, 세션은 서버입니다.
  • 보안성은 쿠키가 저장위치가 클라이언트라는 점에서 스니핑을 당할 우려가 있기 때문에 세션측이 좀 더 좋습니다.
  • LifeCycle은 쿠키는 브라우저가 종료되어도 쿠키에 저장된 만료일(저장기간) 값이 남아있으면 존재하고, 세션은 브라우저 종료 시, 만료기한에 상관없이 종료됩니다.
  • 속도측은 세션이 서버에 정보가 있기 때문에, 쿠키측이 더 빠릅니다. 하지만, 사용자가 많아질수록 서버 메모리를 많이 차지합니다.
  1. 추가!) 브라우저 저장소(웹 스토리지)
  • 서버전송 없이 클라이언트에 데이터를 저장할 수 있도록 HTML5부터 추가된 저장소로, 오직 문자형 데이터 타입만 지원합니다.

  • 쿠키는 서버가 클라이언트에게 전송하는 데이터 파일로, [이름/값/만료일자] 등 데이터를 포함합니다. 모든 브라우저에서 지원되나, 매번 서버에 전송되고, 저장용량이 작으며, 보안에 취약합니다.

  • 웹 스토리지는 쿠키의 단점을 보완하려 등장한 개념입니다.

  • 웹 스토리지는 클라이언트에서 저장만 할 뿐, 서버로 전송하지 않기 때문에 전송에 따른 위험이 없습니다.

  • 웹 스토리지는 지속성에 따라 두 가지로 나뉘는데, 로컬 스토리지(Local Storage)는사용자가 데이터를 지우지 않는 이상, 브라우저나 OS를 종료해도 계속 브라우저에 남아있습니다. 즉, 영구적 저장 특성을 가집니다.

  • 하지만, 세션 스토리지는 데이터가 브라우저 탭에 종속되기 때문에, 윈도우나 브라우저 탭을 닫을 경우 제거됩니다.

  1. 캐시
  • 리소스 파일들의 임시저장소

  • 같은 웹페이지에 접속할 때, 이전에 사용되었던 데이터는 다시 사용될 가능성이 높다라는 생각을 기초로 해서 다시 사용될 확률이 있는 데이터들을 빠르게 접근 가능한 저장소에 저장하는 것이에요!

  • 보통 이러한 리소스의 대상은 이미지, 비디오 오디오, CSS/JS 등이에요 이런건 데이터 사용량도 좀 들고, 시간도 걸리니까 매번 서버에서 불러오면 시간이 너무 오래 걸리는 걸 대상으로 해요. 또, 변경사항이 크지 않아요!


🍕 세션 vs 토큰 vs 쿠키?

https://www.youtube.com/watch?v=tosLBcAX1vk

Cookies vs Tokens ?

영타 연습만 한 게 아니길 바랍니다..

This question is itself sort of wrong. And I think it comes from not knowing how cookies work.

Cookies are how a server can put data on your browser to remember something about you. When you go to a website, your browser will make a request to a server. Then server will replay with a response. The response will have all the data and the code required, to show the pages that you're looking for. And also on that response, the server can give the browser some cookies to save. From now on, after you get the cookies in your browser, everytime you go to that website, the cookies are going to also be sent on that request. Cookies are limited by domain. So, for example, all the cookires Youtube.com gives you are only gonna ve sent to Youtube.com. Cookies are also have an expiration date. Some of them expire in a day, in a week, or whenever the server wants to. Cookies can be used to remember all sorts of things. They are not actually only related to authentication. For example, you change the language, the server can give you the cookies that will rememver what language you chose. So then, the next time that you visit the website again, the cookie is going to go with a request, so the server will be able to give you the page in the language you want.

Sessions vs Tokens

To understand why we need sessions and tokens, we need to remember HTTP, the protocol we use to go to a website, that protocol is stateless. Stateless means every request that goes to the server is treated independently from the previous ones. There's no link between requests. There is no memory. After a request finishes, the server will forget who you are. Because the server forgets everything aboout you once the request's finished, we have to remind this server who we are, every request we make.

One way to do this is by using sessions. So, if we have a user name called 'Nico', and we want to log in, we're going to send the username and the password to the server. If the password is correct, the server will create a recored in a sessions DB, for the user 'Nico'. That session will have a unique ID, that session ID will be sent back to our browser, using cookies as a transportation method and there, it will be sasved. So when we navigate to another page on that same website, our browser is going to sned the cookie that has the session ID back to the server. Because as we know, cookies are sent automatically, the server's going to look at the cookies that are coming in, and will see there's incoming cookie with a session ID. Still, at this point, server doesn't know who we are. The server only knows that there's somebody making a request and that somebody has a cookie with a session ID. with that session ID, the server will go and look at the sessions DB. There, the server will find that this ID belongs to 'Nico', the user, only then, the server will be able to show us a message saying 'Welcome, Nico'. And again, after response is over, everything's finished, when we navigate to another page, the whole process will happen again. The important thing to remember here is that all the information anout the user is on the server side, on the DB. The user only has a session ID. That's it.

As we can see, the cookie is just a transportation method taht we use to send and receive the session ID that is on our DB. We can still use session when making iOS, Android apps, but we can not use cookies, of course, because cookies only exist on browsers, not on native apps. In this context, people will refer to this as a token.

We'll be sending a token to server. The token is just a string that looks really weird. And then we have to send it to the server, and the server is going to take the token and look in the sessions DB for the person who has the token. The most important thing to remeber anout sessions is that ter server has to use DB resources to keep track of all the people that are logged in. That also means that, with every request that comes in, the server has to take the cookie, look at the session ID, search the session ID for the user and then you can continue you can continue. That means, hitting the DB or hitting the sessions DB EVERYTIME there is a request, meaning the more users are logged in, the more DB resources we need. And this is when introduce JWT.

JWT

JWT is a tokend format and if you use JWT to authenticate your users, there's no need to have sessions DB and the server doesn't have to work that hard to authenticate a user. Remember? A token is just a very weird looking text that we get from the server and that we jave to send on every request. Let's talk about the difference between JWT and session by looking at the login example one more time.

If we have a username 'Nico', and we want to log in, we will send the username and the password to the server. That is same as before. If the username and password are correct, the server will take the ID of the user, for example, and it will sign it, usaing a signature algorithm. The server will send us the signed information as a string. Here is what a JWT looks like. It's very longer, longer than a an average session ID that will be used when we send cookies. This is also because, cookies have a space limit. JWTs don't. They can be very big. So, we log in just like before, but instead of hitting the database, all that server needs to do is signing some information and giving it to us. Now, if you wanna make a request to server, just like when we're using session IDs, we have to send that token or signed information to the server, to remind the server who we are. When the server reveives our token, the server is going to check if the signature is valid, which basically means nobody modified the toen, and if it is, the server will trust the token and it will see who we are. Ths is the biggest difference between maing user authentication with sessions and JWT.

With sessions, the server just gives us session ID. All the information anout the session and the user is contained in the session on the DB. And when we request the page to the server, the server will search for that session ID, on the sessions DB.

With JWT, the server will put the information needed to identify us in the token itself, and then give it to us. When we request the page, the server will just verify the signature to see if we haven't modified the token. No need to search on the DB. Also, keep in mind, JWT is not encrypted. It is signed but not encrypted (encrypted means nodody can see in the content, understand what's going on). In the case of JWT, anybody can open JWT and look at the conet it has inside. So we shouldn't put any secret information in JWT. And again, this is ok. The point is not to keep the information secret, but to sign the token and verify that nobody has modified it.

Pros and Cons of Authentication with Sessions and with JWT

When we use sessions, the server keeps the track of all the peple that are logged in on the sessions DB. Having the sessions in our sessions DB allows us to build features that our applications need. For example, if you need to force a logout, kick out a user out of your app, you can just delete the session from the DB. Or you can do what Instagram does. It shows a list of all the devices that you've logged in from, so you can delete or force logout of the devices that you don't reconize any more.
Or Nextflix, they limit the amount of people that can share an account and it also knows how many people are logged in and watching. All these features are possible because of the server's keeping track of who's logged in and because we have sessions DB. But Remember, if we want to do this, we want to keep track of all the people that are logged in. We have to have DB and that is one more thing you're going to have, one more thing you have to pay for. Plus, the more users you get, the more DB you need. But most people use redis.

With JWT, the server doesn't keep track of tokens that it has created by default. All that server knows is if a token is valid or not. That's it. With JWT, you don't have to pay fo an extra sessions DB, but that also means you can not build those kinds of features that we talked about. You can not force somebody out. Because their token ins going to be vaild as long as it hasn't expirted (토큰 만료 전까지는 살아있다)
This deosn't mean JWT sucks. It's actully pretty good. A great way of signing data and giving the data to the user and then when receiving the data back, we can verify if the data has been modified or not, without having to need a DB. Super cool Featuer. (10분 21초)

profile
아무튼, 개발자

0개의 댓글