LoginSignup
64
44

More than 3 years have passed since last update.

【Rails】 API開発で『Can't verify CSRF token authenticity』といわれたときの対応

Last updated at Posted at 2019-08-22

現状の問題

RailsでAPI開発をしている際にエンドポイントを叩いたら以下のようなエラーが出ました。

Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 22ms (ActiveRecord: 0.0ms)

CSRFトークン認証ができなかったという内容のエラーです。

解決方法

方法1. application_controller.rbを修正

controllers/application_controller.rbを見ると以下のようなコメントがあります。

Prevent CSRF attacks by raising an exception.
For APIs, you may want to use :null_session instead.

コメントに従い、以下のように変更すれば問題は解決します。

- protect_from_forgery with: :exception
+ protect_from_forgery with: :null_session

この変更により、CSRF対策が『例外の発生』から『セッションのクリア』になります。
『セッションのクリア」の場合、処理は継続されるためAPIのエンドポイントを叩いたら結果が返ってくるようになります。

方法2. APIで利用するcontrollerを修正

APIで利用するcontrollerに対して以下のメソッドを追加します。

skip_before_action :verify_authenticity_token

こちらのほうが、application_controller.rbを修正するのに比べて影響範囲が限定的になります。

さいごに

ツイッター(@nishina555)やってます。フォローしてもらえるとうれしいです!

64
44
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
64
44