簡體   English   中英

在 Sinatra 中使用標頭進行身份驗證

[英]Authenticate using headers in Sinatra

如果標題之一不匹配,如何比較 sinatra 中的標題並停止代碼/腳本?

假設我有一個名為TOKEN: 666的標頭,我想比較向 sinatra 發出的任何請求,並檢查“TOKEN”是否存在且等於“666”,然后繼續執行代碼,如果不只是返回 401。

答案很簡單:

默認情況下,Sinatra 偵聽端口 4567,因此我只是確保它綁定到所有接口,以防萬一我想從其外部 IP 地址調用它並禁用任何詳細錯誤輸出,如下所示:

監聽器

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 aka 200 OK,設置在塊的末尾,因為當有人向 sinatra 發送請求時,它應該返回一些東西,否則會發生 500 內部服務器錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM