在 Sinatra 中使用 headers 进行身份验证
Authenticate using headers in Sinatra
我如何比较 sinatra 中的 header 并在其中一个 header 不匹配时停止 code/script?
假设我有一个名为 TOKEN: 666
的 header
我想比较对 sinatra 发出的任何请求并检查 "TOKEN" 是否存在并等于“666”然后继续执行代码,如果不只是 return 401.
答案很简单:
默认情况下,Sinatra 在端口 4567 上侦听,所以我只是确保它绑定到所有接口,以防万一我想从其外部 IP 地址调用它并禁用任何详细的错误输出,如下所示:
listener.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
请注意,在比较 header 值时,必须始终包含 HTTP,然后是您的 header - Link
例子
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 是 header 名称
额外
如果你不知道发送给sinatra的header名称是什么那么你可以通过在之前添加以下内容来检查所有请求内容if语句向上:
p request.env
然后再次尝试发送请求,找到您的 header 并根据它进行比较。
注意:status :ok
又名 200 OK,设置在块的末尾,因为当有人向 sinatra 发送请求时它应该 return 一些东西,否则会发生 500 内部服务器错误。
我如何比较 sinatra 中的 header 并在其中一个 header 不匹配时停止 code/script?
假设我有一个名为 TOKEN: 666
的 header
我想比较对 sinatra 发出的任何请求并检查 "TOKEN" 是否存在并等于“666”然后继续执行代码,如果不只是 return 401.
答案很简单:
默认情况下,Sinatra 在端口 4567 上侦听,所以我只是确保它绑定到所有接口,以防万一我想从其外部 IP 地址调用它并禁用任何详细的错误输出,如下所示:
listener.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
请注意,在比较 header 值时,必须始终包含 HTTP,然后是您的 header - Link
例子
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 是 header 名称
额外
如果你不知道发送给sinatra的header名称是什么那么你可以通过在之前添加以下内容来检查所有请求内容if语句向上:
p request.env
然后再次尝试发送请求,找到您的 header 并根据它进行比较。
注意:status :ok
又名 200 OK,设置在块的末尾,因为当有人向 sinatra 发送请求时它应该 return 一些东西,否则会发生 500 内部服务器错误。