DuendeSoftware / Support

Support for Duende Software products
21 stars 0 forks source link

RFC on storing access tokens in cookies vs server sessions #1384

Closed catesandrew closed 1 month ago

catesandrew commented 2 months ago

I'm looking for feedback on storing access tokens in cookies vs server sessions.

Storing access tokens in cookies instead of server sessions offers several advantages, including reducing hardware requirements and simplifying maintenance. After the OAuth agent retrieves the tokens, the backend can issue cookies with SameSite=Strict, HttpOnly, Secure, and a specific path for added security.

An example of a secure cookie setup might look like this:

Set-Cookie: token=encrypted-value; SameSite=Strict; Secure; HttpOnly

Since cookies can persist on the file system even after the browser closes, it’s crucial to store only encrypted tokens in cookies. This ensures that even if cookies are accessed, the tokens remain protected. By returning encrypted tokens via the Set-Cookie header, this approach also eliminates the need for a Redis cluster, further simplifying the infrastructure.

RolandGuijt commented 2 months ago

Everything you state here is correct. Server-side sessions indeed involve extra steps on the server like retrieving the current user session which increase hardware requirements. But they offer significant advantages too:

When these advantages are not relevant in your situation I would opt for non server-side session scenario. If you want to read more on the topic take a look here. This is about IdentityServer's server-side session feature but the concept is the same.

Is this the feedback you are looking for?

catesandrew commented 2 months ago

Yes, thank you. That was excellent feedback. Another question is, when we use a cookie, are we not now open to risk of XSRF (or CSRF) attacks? Its like a game of whack a mole. 😆 🤣

RolandGuijt commented 2 months ago

😆 Please keep in mind that when using server-side session there's still a session cookie. So it doesn't help with CSRF.

What does help against CSRF is something you already mentioned: SameSite cookies. By default the cookie (doesn't matter if server-side sessions is on or off) is issued as a SameSite cookie with the setting lax. That means when doing cross site requests the cookie will not be sent except for GET requests. In general this suffices as long as there aren't any GET request that can change the state of the system. If you don't want the exception you can set the cookie to SameSite mode strict.

RolandGuijt commented 1 month ago

@catesandrew Are your questions answered? If not please add a comment else I'd like to close this issue.

RolandGuijt commented 1 month ago

Closing the issue for now but feel free to reopen if you would like to add anything.