Skip to content

Instantly share code, notes, and snippets.

@mikeappell
Last active September 25, 2024 17:29
Show Gist options
  • Save mikeappell/e29ade0f91d3c71e8c966e058fa5805b to your computer and use it in GitHub Desktop.
Save mikeappell/e29ade0f91d3c71e8c966e058fa5805b to your computer and use it in GitHub Desktop.
Generating an Azure SAS token, reading from Service Bus, using Ruby
class ServiceBusWrapper
def read_service_bus_event
Faraday.delete("#{ service_bus_queue_endpoint }/messages/head", {}, service_bus_headers)
end
private
def service_bus_headers
{
'Authorization' => service_bus_sas_token,
'Content-Type' => 'application/atom+xml;type=entry;charset=utf-8',
}
end
def service_bus_sas_token
encoded_uri = CGI.escape(service_bus_queue_endpoint)
expiry = 1.minute.from_now.to_i.to_s # Decide on this expiry yourself.
string_to_sign = "#{ encoded_uri }\n#{ expiry }"
signed_string = OpenSSL::HMAC.digest('sha256', sas_key_value, string_to_sign)
signature = CGI.escape(Base64.strict_encode64(signed_string))
"SharedAccessSignature sig=#{ signature }&se=#{ expiry }&skn=#{ sas_key_name }&sr=#{ encoded_uri }"
end
def service_bus_queue_endpoint
'https://your-service-bus-domain.servicebus.windows.net/your-queue-name'
end
def sas_key_name
'YourSharedAccessPolicyNameHere'
end
def sas_key_value
ENV['sas_key_value']
end
end
@mikeappell
Copy link
Author

mikeappell commented Sep 25, 2024

This took a bit of time to get working, since Azure no longer maintains any sort of Ruby SDK.

Steps are:

  • In Azure, have a service bus namespace. This comes with an existing Shared Access Policy (under Settings), but I recommend creating one under the specific Queue you'll be reading from instead (more restricted permissions.)
    • Policy can likely have Send and Listen permissions, unlikely you need Manage.
    • Policy name is added to code as sas_key_name.
    • Add queue endpoint to code as service_bus_queue_endpoint.
  • Copy the Primary Key from the policy, add it securely to your application (accessed via ENV, here referred to as sas_key_value.)
  • Decide on an expiry time. This is how long the SAS token will be valid for. Consider whether you're using the token yourself, are sending it to a client, etc.
  • Code should otherwise work as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment