ASP.Net Core 2.1 API JWT cookie-less sessions?

2019-09-02 20:20发布

Is there such thing? Can this be done? Have sessions based on the JWT token and not on cookies? Session.Ids change for me on every request. Is there any way of knowing the session without cookies?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-02 21:20

HTTP is a stateless protocol. That means each request is treated uniquely as if the client had never made a request before. Sessions are a way of faking state. The way they work is when the server needs to maintain state, it creates a session and sends the id of that session to the client via a cookie. A cookie is just a response header that indicates that the client should persist a certain piece of data and then send it back to the server with each subsequent request. The client (web browser), then, does this: saves the cookie and sends the cookie back with each request. The server receives the cookie in the request headers, uses it to look up the session and "restores" it, giving the appearance of state.

The important part is the data, i.e. session id, not necessarily the "cookie". In a sense, that means you could potentially replace the cookie with some other mechanism, as long as the client and server still pass the session id back and forth, you're fine. However, cookies are that mechanism for web browsers. There is nothing else in the web browser world that will automatically send data back to the server each time a user navigates to a different page (sends a request). If this were an API with a generic client involved, and a programmer on the other end deciding how each request will be formatted, then you can handle it however you want. And indeed, APIs don't typically utilize cookies for this very reason - there's usually better ways to do things than passing cookies back and forth when you have full control over the request. That is definitely not the case with a web browser, so traditional websites need cookies to maintain state.

JWT is actually irrelevant in this discussion. It's merely a way of formatting data. It is not a replacement for cookies. Your cookies could be JWTs, and in many modern web apps they actually are, but the server still sends a Set-Cookie header with that, and the client still saves it locally and sends it back with the Cookie header.

查看更多
登录 后发表回答