我有一個 Rails 專案,我正在使用 gem http_logger,我需要屏蔽請求標頭和請求正文和回應中的敏感資訊。
Rails.application.config.filter_parameters
不這樣做,因為我在一個單獨的執行緒中提出了 Rails 請求之外的請求。
我需要一種方法來用 [FILTERED] 替換字串中的“access_token”和“client_secret”
示例字串:
Response body {"access_token":[FILTERED],"scope":"create:foo","expires_in":86400,"token_type":"Bearer"}
要么
Request body {"client_id":"fn23uf32u9f34","client_secret":[FILTERED],"audience":"audience","grant_type":"client_credentials"}
對于這兩種情況,我都可以使用兩個單獨的正則運算式。
uj5u.com熱心網友回復:
您可以使用正則運算式:
rgx = /("(?:access_token|client_secret)":)"[^"] "/
在
str.sub(rgx, '\1[FILTERED]')
str = 'Response body {"access_token":"oigoi34oi34thj3489we89e2","scope":"create:foo","expires_in":86400,"token_type":"Bearer"}'
puts str.sub(rgx, '\1[FILTERED]')
顯示
Response body {"access_token":[FILTERED],"scope":"create:foo","expires_in":86400,"token_type":"Bearer"}
str = 'Request body {"client_id":"fn23uf32u9f34","client_secret":"jibberish","audience":"audience","grant_type":"client_credentials"}'
puts str.sub(rgx, '\1[FILTERED]')
顯示
Request body {"client_id":"fn23uf32u9f34","client_secret":[FILTERED],"audience":"audience","grant_type":"client_credentials"}
正則運算式演示
正則運算式可以分解如下。
( # begin capture group 1 \
" # match literal
(?: # begin non-capture group
access_token # match literal
| # or
client_secret # match literal
)
": # match literal
)
" # match literal
[^"] # match one or more characters other than
# double-quotes, as many as possible
" # match literal
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440699.html
