Skip to content

Instantly share code, notes, and snippets.

@MarioRuiz
Last active February 6, 2019 14:50
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 MarioRuiz/d3525185024737885c0c9afa6dc8b9e5 to your computer and use it in GitHub Desktop.
Save MarioRuiz/d3525185024737885c0c9afa6dc8b9e5 to your computer and use it in GitHub Desktop.
How to get the OAuth2 token for Microsoft Azure using Ruby and add it to your Http connection header. Install in command line first: gem install nice_http or in case you use linux: sudo gem install nice_http
require 'nice_http'
require "addressable/uri"
# Create on management.azure.com a new directory or
# select the one you want
# Create an application on that directory if you want to
# Be sure api permissions are the ones you need,
# for example Access Azure Service Management
# Get the client_id and the tenant_id
# Create a client secret and get it
client_id = "YOUR CLIENT ID"
tenant_id = "YOUR TENANT ID"
client_secret = "YOUR CLIENT SECRET"
resource = 'https://management.azure.com/' #The resource you want to log in
server = 'https://login.microsoftonline.com'
path = "/#{tenant_id}/oauth2/token"
uri = Addressable::URI.new
uri.query_values = {
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret,
resource: resource
}
http = NiceHttp.new(server)
req = {
path: path,
data: uri.query.to_s
}
resp = http.post(req)
puts "#{resp.code}: #{resp.message}"
access_token = resp.data.json(:access_token)
puts access_token
# for connecting to your resource:
NiceHttp.headers = { Authorization: "Bearer #{access_token}" }
# from now on all NiceHttp connections you create will have the Bearer token
http_res = NiceHttp.new(resource)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment