LoginSignup
2
1

More than 5 years have passed since last update.

RailsでSlackのWebhookを受ける時に protect_from_forgery でトークンを検証する

Last updated at Posted at 2017-06-23

verify_authenticity_token をオーバーライドしてトークンの検証をしてあげれば良い。
たぶん他のサービスのWebhookにも応用できる。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end
app/controllers/slack_controller.rb
class SlackController < ApplicationController

  private

  def slack_token
    fail NoMethodError.new('please overwrite')
  end

  def valid_slack_token?
    params[:token] == slack_token
  end

  def verify_authenticity_token
    unless valid_slack_token?
      logger.warn "WARNING: Can't verify Slack token authenticity" if logger
      handle_unverified_request
    end
  end
end
app/controllers/slack/webhooks_controller.rb
class Slack::WebhooksController < SlackController
  def create
    head :ok
  end

  private

  def slack_token
    ENV['SLACK_TOKEN']
  end
end
2
1
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
1