Skip to content

Commit

Permalink
Add HttpOnly option to cookie (#39)
Browse files Browse the repository at this point in the history
* Add :httponly cookie option

* Add :httponly cookie option to README.md

* Add test for :httponly cookie option
  • Loading branch information
Lubo-mir authored Sep 21, 2020
1 parent effd9b1 commit a29bd58
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand Down
6 changes: 6 additions & 0 deletions lib/angular_rails_csrf/concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test/angular_rails_csrf_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit a29bd58

Please sign in to comment.