1

Rails allow opting out of the SameSite cookie attribute when setting a cookie

 1 year ago
source link: https://blog.saeloun.com/2023/02/01/rails-allow-opting-out-of-samesite
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

What is SameSite cookie attribute?

Cookies are small text files that are stored on a user’s device to remember their preferences, login information, and other data. SameSite is a cookie attribute that can be used to prevent cross-site request forgery (CSRF) attacks. To ensure that cookies are transmitted securely and only to the intended website, the HTTP specification includes the “SameSite” cookie attribute. This attribute allows websites to specify whether or not a cookie should be sent along with cross-site requests.

Rails 6.1 introduced the SameSite cookie attribute to the cookies API. However, this attribute was set to :lax by default, which meant that cookies were not sent along with cross-site requests. Although, the docs mentioned that this attribute could be set as nil. This didn’t work as it would fallback to :lax by default.

Before

Let’s assume in our Rails application, we want to set a cookie for language set as en and we want to ensure that this cookie is sent along with cross-site requests. To do this we would write the following code:

cookies[:language] = { value: 'en', same_site: nil }

However, this would not work since same_site would fallback to :lax by default.

After

However in the upcoming Rails 7, this would work as expected.

cookies[:language] = { value: 'en', same_site: nil }

The above code would now correctly set the SameSite cookie attribute to nil and the cookie would be sent along with cross-site requests. This will ensure that the language cookie is sent with requests to the application, regardless of the source of the request. This allows the app to remember the user’s preferred language and provide a more personalized experience.

The ability to opt out of the same_site is a valuable addition to the Rails framework, and it provides more control over the behavior of cookies in our application.

Check out the PR for more details.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK