使用 VCR 过滤掉 JWT 和 Bearer 令牌

Pez*_*lio 3 ruby google-drive-api vcr

我正在通过Google Drive Ruby gem使用Google Drive API并使用VCR来记录请求。

我正在通过 JWT 进行身份验证,并希望过滤掉 JWT 请求和返回的不记名令牌。

由于我不知道 Google 在运行时给我的 JWT 令牌或不记名令牌,因此我无法使用filter_sensitive_data. 因此,在测试运行后,我需要过滤以下乱七八糟的代码,以便对我的磁带进行消毒:

after(:each) do |example|
  # Filter out JWT and bearer tokens from requests
  if VCR.current_cassette.recording?
    interactions = VCR.current_cassette.new_recorded_interactions
    # Remove JWT token
    interactions.first.request.body.gsub! /(?<=assertion\=).*/, '<JWT_TOKEN>'
    # Get and replace access token from body
    body = JSON.parse(interactions.first.response.body)
    access_token = body['access_token']
    body['access_token'] = '<ACCESS_TOKEN>'
    interactions.first.response.body = body.to_json
    # Replace access token in each auth request
    interactions.drop(1).each do |i|
      i.request.headers['Authorization'][0].gsub!(access_token, '<BEARER_TOKEN>')
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我的问题是真正的两个人 - 1) 还有另一种方法可以做到这一点吗?2)这甚至有必要吗?想法赞赏!

Sla*_*lag 8

我使用了 filter_sensitive_data 并想出了这个:

VCR.configure do |config|
  config.filter_sensitive_data('<BEARER_TOKEN>') { |interaction|
    auths = interaction.request.headers['Authorization'].first
    if (match = auths.match /^Bearer\s+([^,\s]+)/ )
      match.captures.first
    end
  }
end
Run Code Online (Sandbox Code Playgroud)

当我测试时,盒式磁带内的 auth 标头如下所示:

Authorization:
- Bearer <BEARER_TOKEN>
Run Code Online (Sandbox Code Playgroud)

值得注意的假设:

  • HTTP 请求应该只包含一个 auth 标头
  • 但是,该标头可能包含多个以逗号分隔的身份验证
  • 上面的代码只捕获以“Bearer”开头的身份验证
  • 您可以针对“Bearer”以外的其他类型进行调整