From a29bd58f8f955072ca661811a5c7fc6767ebab9b Mon Sep 17 00:00:00 2001 From: Lubomir <13518256+Lubo-mir@users.noreply.github.com> Date: Mon, 21 Sep 2020 15:17:54 +0200 Subject: [PATCH] Add HttpOnly option to cookie (#39) * Add :httponly cookie option * Add :httponly cookie option to README.md * Add test for :httponly cookie option --- README.md | 14 ++++++++++++++ lib/angular_rails_csrf/concern.rb | 6 ++++++ test/angular_rails_csrf_test.rb | 12 ++++++++++++ 3 files changed, 32 insertions(+) diff --git a/README.md b/README.md index 50ae10a..22bfee0 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,20 @@ end Please note that [Safari is known to have issues](https://bugs.webkit.org/show_bug.cgi?id=198181) with SameSite attribute set to `:none`. +### HttpOnly Cookie + +To set a "httponly" flag for the cookie, set the `angular_rails_csrf_httponly` option to `true`: + +```ruby +# application.rb +class Application < Rails::Application + #... + config.angular_rails_csrf_httponly = true +end +``` + +`angular_rails_csrf_httponly` defaults to `false`. + ### Exclusions Sometimes you will want to skip setting the XSRF token for certain controllers (for example, when using SSE or ActionCable, as discussed [here](https://github.com/jsanders/angular_rails_csrf/issues/7)): diff --git a/lib/angular_rails_csrf/concern.rb b/lib/angular_rails_csrf/concern.rb index bc6ca49..6c1dd76 100644 --- a/lib/angular_rails_csrf/concern.rb +++ b/lib/angular_rails_csrf/concern.rb @@ -14,12 +14,14 @@ def set_xsrf_token_cookie config = Rails.application.config same_site = same_site_from config + httponly = httponly_from config secure = secure_from config cookie_options = { value: form_authenticity_token, domain: domain_from(config), same_site: same_site, + httponly: httponly, secure: same_site.eql?(:none) || secure } @@ -37,6 +39,10 @@ def same_site_from(config) config.respond_to?(:angular_rails_csrf_same_site) ? config.angular_rails_csrf_same_site : :lax end + def httponly_from(config) + config.respond_to?(:angular_rails_csrf_httponly) ? config.angular_rails_csrf_httponly : false + end + def secure_from(config) config.angular_rails_csrf_secure if config.respond_to?(:angular_rails_csrf_secure) end diff --git a/test/angular_rails_csrf_test.rb b/test/angular_rails_csrf_test.rb index 26954b6..d3b2142 100644 --- a/test/angular_rails_csrf_test.rb +++ b/test/angular_rails_csrf_test.rb @@ -78,6 +78,18 @@ def config.angular_rails_csrf_domain end end + test 'the httponly flag is set if configured' do + config = Rails.application.config + config.define_singleton_method(:angular_rails_csrf_httponly) { true } + + get :index + assert @response.headers['Set-Cookie'].include?('HttpOnly') + assert_valid_cookie + assert_response :success + ensure + config.instance_eval('undef :angular_rails_csrf_httponly', __FILE__, __LINE__) + end + test 'same_site is set to Lax by default' do get :index assert @response.headers['Set-Cookie'].include?('SameSite=Lax')