Ruby 用于屏蔽敏感信息的正则表达式
Ruby regex for masking sensitive information
我有一个 rails 项目,我正在使用 gem http_logger
,我需要在请求 headers 和请求 body 中屏蔽敏感信息和回应。
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"}
对于这两种情况,我都可以使用两个单独的正则表达式。
您可以使用正则表达式:
rgx = /("(?:access_token|client_secret)":)"[^"]+"/
在
str.sub(rgx, '[FILTERED]')
str = 'Response body {"access_token":"oigoi34oi34thj3489we89e2","scope":"create:foo","expires_in":86400,"token_type":"Bearer"}'
puts str.sub(rgx, '[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, '[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
我有一个 rails 项目,我正在使用 gem http_logger
,我需要在请求 headers 和请求 body 中屏蔽敏感信息和回应。
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"}
对于这两种情况,我都可以使用两个单独的正则表达式。
您可以使用正则表达式:
rgx = /("(?:access_token|client_secret)":)"[^"]+"/
在
str.sub(rgx, '[FILTERED]')
str = 'Response body {"access_token":"oigoi34oi34thj3489we89e2","scope":"create:foo","expires_in":86400,"token_type":"Bearer"}'
puts str.sub(rgx, '[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, '[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