Skip to content

Instantly share code, notes, and snippets.

@jacobbednarz
Last active February 12, 2019 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobbednarz/e7a7427572a54d6e28347ae1584231c2 to your computer and use it in GitHub Desktop.
Save jacobbednarz/e7a7427572a54d6e28347ae1584231c2 to your computer and use it in GitHub Desktop.
# Cloudflare Access Service tokens example.
#
# This is a code sample for using Cloudflare Access using service
# tokens. To execute this sample, you'll need to setup a new service
# token (client ID and client secret) as well as an Access Policy that
# allows the non-identity to access the resource. For assistance setting
# up the Cloudflare Access Service Token and the Access Policy, please
# refer to the documentation linked below.
#
# Prerequisites:
#
# - Ruby (not EOL'd)
# - Faraday gem (`gem install faraday`)
#
# Required Environment Variables:
#
# - CF_CLIENT_ID: The client ID value from Cloudflare Access.
# - CF_CLIENT_SECRET: The client secret provided by Cloudflare Access.
# - URL: The full URL that is sitting behind Cloudflare Access that
# you would like to access. This can be a domain or a domain with a
# path.
#
# Usage:
#
# $ export CF_CLIENT_ID="abc123.access.example.com" \
# CF_CLIENT_SECRET="abcdef1234" \
# URL="https://secret.example.com"
#
# $ ruby service_tokens_example.rb
#
# Blog: https://blog.cloudflare.com/give-your-automated-services-credentials-with-access-service-tokens/
# Docs: https://developers.cloudflare.com/access/connecting-to-apps/service-token/
require "faraday"
cf_client_id = ENV.fetch("CF_CLIENT_ID")
cf_client_secret = ENV.fetch("CF_CLIENT_SECRET")
url = ENV.fetch("URL")
response = Faraday.new(
url: url,
headers: {
'CF-Access-Client-Id' => cf_client_id,
'CF-Access-Client-Secret' => cf_client_secret
}
).get
# The JWT token we need to authorised to Cloudflare Access is in the
# `Cookie` HTTP header. There could be other cookies in there so we
# extract everything from the `CF_Authorisation=` string and the
# trailing semi colon.
cookies = response.headers['set-cookie']
jwt_authorisation_value = cookies.match(/.*(CF_Authorization=[\w\-\.]+);$/).captures
# We shouldn't get here if we've provided the correct credentials *and*
# applied the Access Policy. Should you land here, ensure your
# credentials are correct and the Access Policy is setup.
if jwt_authorisation_value.nil?
raise "CF_Authorization cookie value wasn't found"
end
authorised_response = Faraday.new(
url: url,
headers: { 'Cookie' => jwt_authorisation_value }
).get
# `authorised_response` is now populated with the origin response that
# is behind Cloudflare Access.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment