Last active
September 14, 2022 12:09
-
-
Save jandudulski/f3799ca67b7b08ded0c6 to your computer and use it in GitHub Desktop.
CSRF on Grape
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html | |
module Auth | |
extend ActiveSupport::Concern | |
included do | |
helpers do | |
def session | |
env['rack.session'] | |
end | |
def protect_against_forgery | |
unless verified_request? | |
error!('Unauthorized', 401) | |
end | |
end | |
def verified_request? | |
!protect_against_forgery? || request.get? || request.head? || | |
form_authenticity_token == request.headers['X-CSRF-Token'] || | |
form_authenticity_token == request.headers['X-Csrf-Token'] | |
end | |
def form_authenticity_token | |
session[:_csrf_token] ||= SecureRandom.base64(32) | |
end | |
def protect_against_forgery? | |
allow_forgery_protection = Rails.configuration.action_controller.allow_forgery_protection | |
allow_forgery_protection.nil? || allow_forgery_protection | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Controller < Grape::API | |
include Auth | |
before do | |
protect_against_forgery | |
end | |
resource :something do | |
... | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @jandudulski we made a gem from your gist : https://github.com/KissKissBankBank/grape-forgery_protection