ruby - 在 Sinatra 中使用标头进行身份验证
问题描述
如果其中一个标题不匹配,我如何比较 sinatra 中的标题并停止代码/脚本?
假设我有一个名为TOKEN: 666
我想比较向 sinatra 发出的任何请求并检查“TOKEN”是否存在且等于“666”的标头,然后继续执行代码,如果不只是返回 401。
解决方案
答案很简单:
默认情况下,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 内部服务器错误。
推荐阅读
- c# - 必须在 cosmosdb 删除操作中为此操作提供 PartitionKey 值
- hyperledger-fabric - Hyperledger fabric node sdk register user give me [错误:无法验证第一个证书]
- c++ - 无法在鼠标单击OpenGL时围绕自己的中心旋转对象
- c - 在 macos 上发送太快时丢包
- python - 如何在 selenium 中保留登录状态
- android - 如何重新生成 ios 和 android 文件夹?
- r - 如何在 R 中使用 directlabels 包添加重复标签
- c++ - 多线程程序中的分段错误和 gdb 回溯信息不完整
- javascript - 具有数百个输入的巨大 React 状态数组,状态变化缓慢 onChange
- postgresql - Postgresql 11 扩展 hll 不可用