LoginSignup
4
0

More than 3 years have passed since last update.

phoenixのcsrfチェックを外したい

Posted at

phoenixフレームワークを利用してAPIサーバを立てようとしていたのですが、
フツーにpostリクエストを送ってしまうとcsrfのエラーが発生しました。

invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header

セキュリティ的に、デフォルトでONになっているのは安全でいいですね。
しかし、APIサーバとして稼働させたい時などは、このチェックがあるとアクセスができなくなってしまうため外したい。

routeに設定してあるplug :protect_from_forgeryの記述を消せば発生しなくなるのですが、
消してしまうと、他のURLにも影響が出てしまう。
例えばwebサイトとして動かしている部分とapiサーバが同居してた場合、
どちらかが不利益を被るので、そういう場合どうやって制御すればいいんだろ、と。

で、そういう場合はscope毎に使用するpipelineを変えてあげれば実現できそうでした。

defmodule PhoenixBlogWeb.Router do
  use PhoenixBlogWeb, :router

  # webサーバとして動かす設定
  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  # apiサーバとして動かす設定
  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", PhoenixBlogWeb do
    pipe_through :browser # webアクセス用の設定を使用する

    get "/", PageController, :index
    resources "/articles", ArticleController
  end

  scope "/api", PhoenixBlogWeb do
    pipe_through :api # api用の設定を使用する
    resources "/articles", ArticleController
  end
end

こうすることで、URL毎にCSRF(だけじゃなくてその他のplugに関しても)をON / OFFできます。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0