首页 > 解决方案 > 在 Sinatra 中使用标头进行身份验证

问题描述

如果其中一个标题不匹配,我如何比较 sinatra 中的标题并停止代码/脚本?

假设我有一个名为TOKEN: 666 我想比较向 sinatra 发出的任何请求并检查“TOKEN”是否存在且等于“666”的标头,然后继续执行代码,如果不只是返回 401。

标签: rubyauthenticationhttp-headerssinatra

解决方案


答案很简单:

默认情况下,Sinatra 侦听端口 4567,所以我只是确保它绑定到所有接口,以防我想从其外部 IP 地址调用它并禁用任何详细错误输出,如下所示:

监听器.rb

require "sinatra"

set :bind, "0.0.0.0"
disable :show_exceptions
disable :raise_errors

post "/" do

  # Check if the header matches
  # If it did not match then halt and return code 401 Unauthorized

  if request.env["HTTP_custom_header_name"] != "verystrongpassword"
    halt 401
  end

  #the rest of your code goes here

  status :ok

end

请注意,在比较标头值时,必须始终包含HTTP,然后使用标头的名称 -链接

例子

require "sinatra"

set :bind, "0.0.0.0"
disable :show_exceptions
disable :raise_errors

post "/" do

  # Check if the header matches
  # If it did not match then halt and return code 401 Unauthorized

  if request.env["HTTP_X_GIT_SECRET"] != "d4c74594d841139328695756648b6bd6"
    halt 401
  end

  data = JSON.parse request.body.read
  p data

  status :ok

end

其中X_GIT_SECRET是标头名称

额外的

如果您不知道发送到 sinatra 的标头的名称是什么,那么您可以通过在 if 语句之前添加以下内容来检查所有请求内容:

p request.env

然后尝试再次发送请求,找到您的标头并根据它进行比较。

注意:status :ok又名 200 OK,设置在块的末尾,因为当有人向 sinatra 发送请求时它应该返回一些东西,否则会发生 500 内部服务器错误。


推荐阅读