如何在Phoenix框架中有选择地禁用CSRF检查

N. *_*ola 18 csrf elixir csrf-protection phoenix-framework

我正在尝试创建指向我网站的Facebook页面标签.Facebook将HTTP POST请求发送到我网站的网址.这里的问题是服务器有一个内置的CSRF检查,它返回以下错误:

(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`
Run Code Online (Sandbox Code Playgroud)

服务器需要Facebook不能拥有的CSRF令牌.所以,我想有选择地为路径www.mywebsite.com/facebook禁用CSRF.

我怎么能在Phoenix Framework中做到这一点?

Gaz*_*ler 27

Plug.CSRFProtection是你的路由器启用protect_from_forgery.这在browser管道中默认设置.添加插件后,无法禁用它,而是必须首先设置它.您可以通过将其移出browser并仅在需要时将其包括在内来完成此操作.

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
Run Code Online (Sandbox Code Playgroud)