如何在Phoenix框架中有选择地禁用CSRF检查 [英] How to selectively disable CSRF check in Phoenix framework

查看:61
本文介绍了如何在Phoenix框架中有选择地禁用CSRF检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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`

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

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.

如何在Phoenix Framework中做到这一点?

How can I do it in Phoenix Framework?

推荐答案

使用protect_from_forgery在路由器中启用了Plug.CSRFProtection.默认在browser管道中设置.一旦添加了插件,就无法禁用它,而不必首先将其设置.您可以通过将其从browser中移出并仅在需要时才包括它来实现.

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

这篇关于如何在Phoenix框架中有选择地禁用CSRF检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆