I'm trying to create a Facebook Page Tab which points to my website. Facebook sends a HTTP POST request to the url of my website. The problem here is that the server has a built-in CSRF check, and it returns the following error:
(Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Forgery Protection) token, make sure all requests include a '_csrf_token' param or an 'x-csrf-token' header`
The server expects a CSRF token that Facebook can't have. So, I want to selectively disable CSRF for the path www.mywebsite.com/facebook.
How can I do it in Phoenix Framework?
You can disable CSRF protection by setting the csrf. protection. enabled system configuration item to the value false. This can be done via REST API.
Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.
Automated Tools for CSRF testingBright's CSRF test first checks if there is any CSRF protection implemented, by checking if the target has “Access-Control-Allow-Origin” header misconfiguration or missing “Origin” header.
Change the setting "AntiForgeryEnabled": true to "AntiForgeryEnabled": false and your Postman requests should work again. Note that you only get the http 500 error on POST, PUT and DELETE requests.
The Plug.CSRFProtection
is enabled in your router with protect_from_forgery
. This is set by default in the browser
pipeline. Once a plug has been added, there is no way to disable it, instead it has to be not set in the first place. You can do this by moving it out of browser
and only including it when it is required.
defmodule Foo.Router do
use Foo.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
#plug :protect_from_forgery - move this
end
pipeline :csrf do
plug :protect_from_forgery # to here
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", Foo do
pipe_through [:browser, :csrf] # Use both browser and csrf pipelines
get "/", PageController, :index
end
scope "/", Foo do
pipe_through :browser # Use only the browser pipeline
get "/facebook", PageController, :index #You can use the same controller and actions if you like
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With