配置POST端点以仅响应cron.yaml请求

时间:2017-01-28 16:36:13

标签: django amazon-web-services cron elastic-beanstalk amazon-sqs

我有一个在Elastic Beanstalk上运行的Django应用程序,并希望每晚都运行一个作业(搜索引擎的重新索引)。根据{{​​3}},我可以使用cron.yaml在适当的时间自动向我的应用发出POST个请求,并配置我的应用以做出适当的响应。

如何确保我的应用仅响应自动生成的请求,而不是对同一网址的随机请求?具体来说,我不希望恶意用户发布并导致应用程序执行操作。

1 个答案:

答案 0 :(得分:0)

您可以检查多项内容,以确保请求来自cron.yaml ...

1)请求将来自localhost

2)User-Agent将包含aws-sqsd

3)请求只应由您的工作人员实例处理。

我使用before_action过滤器在我的控制器中强制执行这些过滤器。代码看起来像这样:

##
# Protect against abuse - requests must have the correct "User-Agent" header,
# come from localhost, and will only be handled by worker instances.
before_action :correct_user_agent
before_action :correct_source
before_action :worker_instance

...controller code here...

private

##
# Confirms the correct User-Agent header was sent.
def correct_user_agent
  return if request.headers.env["HTTP_USER_AGENT"].include?("aws-sqsd")
  head(:forbidden)
end

##
# Confirms the request is coming from localhost.
def correct_source
  return if request.local? || Rails.env.development? || Rails.env.test?
  head(:forbidden)
end

##
# Don't allow requests to be processed in the production web environment, since
# it has a worker instance associated with it.
def worker_instance
  return unless Rails.env.production?
  head(:forbidden)
end