2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CurlでPOSTできない!!RailsのCSRF対策

Last updated at Posted at 2019-09-14

RailsをAPIとして使おうとターミナルからcurlコマンドでPOSTしようとしたがエラった時のメモ

  • curl -X POST localhost:5000/api/tasks -d 'task[name]=fugafuga'をやろうとして以下のエラー

エラー内容

  • 422エラー:Can't verify CSRF token authenticity
  • これを日本語にするとCSRFトークンの信頼性を確認できませんとなる

普通のフォーム入力の場合

こんな感じでhiddenにCSRF対策用のtokenが埋め込まれている
スクリーンショット 2019-09-14 9.16.03.jpg

  • 今回curlコマンドでPOSTしたことによりこのtokenがないことにRailsが怒ったってことか。。。

調査と対応

  • APIで使用する場合...
    • APIはステートレスであるべきなので、認証はすべてのリクエストでサーバー側のセッションを使わずに行われる。
    • なのでAPIのコントローラにはprotect_from_forgeryを追加したくない、実際CSRF攻撃のリスクはほぼない。らしい。
  • 以上のことからapplication_controllerprotect_from_forgery with: :null_sessionを追加してヨシとした。
application_contrller.rb
class ApplicationController < ActionController::Base
    protect_from_forgery with: :null_session
end

補足

  • 以下のように該当のコントローラのこのアクションをprotect_from_forgeryの対象から除外するやり方もあるみたい。
hoge_controller.rb

class HogeController < ApplicationController
  protect_from_forgery :except => [:huga]

  def huga
    ## 処理
  end
end

RailsはAPIで使われることが多いから覚えておこう。
次回はAPI認証をつけるをテーマに執筆予定
以上!!

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?