puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Cookie-based Authentication (Old School) #164

Open puddlejumper26 opened 3 years ago

puddlejumper26 commented 3 years ago

Cookie-based Auth Flow

image

If a user visits a web page (makes a request) and the server detects a session cookie, it will check if it currently has a session stored with the ID from the cookie, and if that object is still valid (whatever that means: not expired, not revoked, not blacklisted, etc.).

If the session is still valid, it will respond with the requested web page (or data). If it finds a session object, that object can contain data in it and with that, the server can "remember" who you are and what you were doing (e.g., if this is an ecommerce store, what products you've added to our shopping cart).

If the session is not valid (or no session cookie was detected) it will respond with some sort of error message saying that the request is "unauthorized".

New sessions can typically be created by sending a username/password combination to a specific endpoint from a login page. If the server can match a user with that username and password, it will generate a new session object on the server and set a cookie on the client with the session's ID for any future requests.

If a user turns off their computer and comes back to the website some time in the future, s/he can either automatically login again (if there is still a cookie in the browser that hasn't expired) or login again through the login page. Once logged in, the user's session can be retrieved again from the data stored on the server, and the user can go on with their business (e.g., continuing to shop after reloading your shopping cart).

This type of setup has worked pretty well for us since the web came out and since we've been visiting web sites that do most of their "thinking" on the server side. Typically this has been a conversation between the user's frontend browser and a corresponding backend server in a one-to-one relationship.

Multi-server Cookie Auth Flow is Broken image

This setup still works, but these days we have many different situations that require different setups (e.g., multiple mobile native apps alongside large single-page web apps contacting multiple backend services, that may be nothing more than json data without a webpage at all). In these types of scenarios, the cookie you get from one server, won't correspond (or even be sent) to another server (let alone the problems that get created with CORS).

在Session会话认证模型中,在用户登录并授权后,服务器将创建客户端唯一的Session。服务器将Session ID返回给客户端,然后客户端将其存储在浏览器的cookie中。在随后的HTTP调用中,cookie将自动包含在HTTP请求头中,服务器将通过cookie中记录的Session ID得知客户端的身份。尽管cookie存储在客户端,但是由于验证是在服务器上完成的,因此该认证模型属于服务器端会话。

链接:https://juejin.im/post/6844904061439836167

Session认证的优点

Session认证的缺点

Drawbacks With Cookie-based Auth

Complex Multi-server Cookie Auth Flow image

Reference