https://github.com/xing/unified_csrf_prevention
Self-healing, stateless and programming language agnostic CSRF prevention library for Rails
https://github.com/xing/unified_csrf_prevention
Last synced: 10 months ago
JSON representation
Self-healing, stateless and programming language agnostic CSRF prevention library for Rails
- Host: GitHub
- URL: https://github.com/xing/unified_csrf_prevention
- Owner: xing
- License: mit
- Created: 2018-06-05T09:30:31.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2018-07-03T22:12:52.000Z (about 8 years ago)
- Last Synced: 2025-09-01T00:20:32.985Z (11 months ago)
- Language: Ruby
- Homepage:
- Size: 17.6 KB
- Stars: 1
- Watchers: 20
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: MIT-LICENSE
Awesome Lists containing this project
README
# Unified CSRF Prevention for Rails
This gem is a drop-in upgrade for request forgery protection in Rails 4 and 5 with the following benefits:
* It is self-healing by design. Whenever a user comes in with an invalid authenticity token, they will have a valid one sent back along with the error response so the next request will succeed. There's no need for the user to reload the page.
* The CSRF prevention is decoupled from the users' sessions that could eventually get wiped out or overwritten, resulting in errors.
* The approach is framework/language agnostic, so the token generated by one application will be accepted by any other, including non-Rails applications (given they implement the same CSRF prevention scheme).
* The mechanism is stateless from the backend's perspective. The data is stored in the browser's cookies, requiring no backend storage.
* The solution design was audited by Xing Security team and [cure53](https://cure53.de).
* It is both React- and jQuery-friendly.
Please read the [Cross-application CSRF Prevention specification](https://github.com/xing/cross-application-csrf-prevention) for design and implementation details.
## Configuring Your Application
1. Add the gem to the `Gemfile`:
```ruby
gem 'unified_csrf_prevention'
```
2. Set the shared secret key configuration value for `production`, `preview` and whatever other environment your have:
```ruby
Rails.application.configure do
# existing configuration settings
config.unified_csrf_prevention_key = '64 random characters'
end
```
3. Replace the unobtrusive scripting adapter that adds the `X-CSRF-Token` header which comes with Rails with this one (assuming jQuery is used):
```js
$.ajaxPrefilter(function(options) {
var token = (document.cookie.match(/(?:^|;\s*)csrf_token=([^;]+)/) || [])[1];
if (token) {
options.headers["X-CSRF-Token"] = token;
}
});
```
Important note: **the token must be read from cookies for each and every frontend request the application makes. It is not acceptable to read the token once and store it in some variable, DOM node or in any other form.**
In other words, please do exactly what the provided snippet does - for any request read the token from the cookie right before the request is sent. Don't try to cache the token, transfer it from the backend, or optimize out the cookie access, otherwise your application could end up using invalid tokens.
If your application uses something different from jQuery to make AJAX calls, please adjust the snippet accordingly. The key parts are running the code before each request is sent, and setting the header with the value read from the cookie. Basically, `$.ajaxPrefilter` and `options.headers` should be replaced with something that works with the library you use instead of jQuery.
If your application for some reason has several different ways to send AJAX requests, you need to adjust all of them.
## Usage
The gem is seamlessly integrated with Rails' built-in request forgery protection mechanism so there's nothing special to be done on top of the regular `protect_from_forgery` controller setting.
Authenticity tokens transferred in hidden inputs as well as per-form authenticity tokens introduced in Rails 5 just work out of the box.
See [Ruby on Rails Security Guide](http://guides.rubyonrails.org/security.html#csrf-countermeasures) for details.
## Testing Controllers with Forgery Protection Enabled
Sometimes it's necessary to test the controller code with the actual forgery protection mechanisms enabled (`allow_forgery_protection` overwritten in tests).
Providing the cookies for requests to make `unified_csrf_prevention` work is a bit of a hassle, so instead it's possible to mock the token validation and thus make the controller accept the supplied token:
```ruby
describe '#some_action' do
context 'when requested with valid csrf token' do
let(:csrf_token) { controller.send(:form_authenticity_token) }
before do
allow(controller).to receive(:valid_token?).with(csrf_token).and_return true
end
it 'executes action' do
post :some_action, authenticity_token: csrf_token
expect(response).to be_ok
end
end
end
```
## Compatibility
The gem is compatible with Rails 4.2, 5.0, 5.1 and 5.2.
## Running Specs
```bash
rubocop
appraisal install
appraisal rspec
```