Skip to content

Instantly share code, notes, and snippets.

@djberg96
Last active April 8, 2018 02:53
Show Gist options
  • Save djberg96/ad863b3bf1109424b1522edb09ecc27a to your computer and use it in GitHub Desktop.
Save djberg96/ad863b3bf1109424b1522edb09ecc27a to your computer and use it in GitHub Desktop.
require 'oauth2'
require 'json'
# Assume I've got the client_id, client_key and tenant_id from somewhere
site_url = 'https://login.microsoftonline.com'
token_url = tenant_id + "/oauth2/token"
auth_url = File.join(site_url, tenant_id, 'oauth2', 'token')
resource_url = 'https://management.azure.com/'
# Ok, no problem
client = OAuth2::Client.new(
client_id,
client_key,
:site => site_url,
:authorize_url => auth_url,
:token_url => token_url
)
# My custom error handler for Faraday, which OAuth2 uses underneath the hood
class MyErrorHandler < Faraday::Response::Middleware
def on_complete(env)
case env.status
when 400..600
raise "OOPS: #{env.status}"
else
env.body
end
end
end
# Ok, seems to work
client.connection do |c|
c.use MyErrorHandler
c.adapter Faraday.default_adapter
end
# Yep, still working
credentials = client.client_credentials
token = credentials.get_token(:resource => resource_url)
# Deliberately use a bogus api-version string
url = 'https://management.azure.com/subscriptions?api-version=2019-09-01'
headers = {
:accept => 'application/json',
:content_type => 'application/json'
}
# An "InvalidApiVersionParameter" is raised. However, oauth2 raises an OAuth2::Error
# instead of using my custom error handler, which is never hooked into.
token.request(:get, url, :headers => headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment