Skip to content

Commit

Permalink
Create example for Microsoft Graph
Browse files Browse the repository at this point in the history
  • Loading branch information
neontuna committed Oct 8, 2018
1 parent 85d7c71 commit 1615568
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 18 deletions.
18 changes: 0 additions & 18 deletions docs/README.md
Expand Up @@ -5,7 +5,6 @@ Makes http fun again!
## Table of contents
- [Parsing JSON](#parsing-json)
- [Working with SSL](#working-with-ssl)
- [Multipart Post](#multipart-post)

## Parsing JSON
If the response Content Type is `application/json`, HTTParty will parse the response and return Ruby objects such as a hash or array. The default behavior for parsing JSON will return keys as strings. This can be supressed with the `format` option. To get hash keys as symbols:
Expand Down Expand Up @@ -104,21 +103,4 @@ class Client
# get("resources", verify_peer: false)
end
end
```

## Multipart Post

Sending a `multipart/form-data` post request with HTTParty is easy, for example to request a bearer token from Microsoft's Graph API:

```ruby
HTTParty.post(
"https://login.microsoftonline.com/tenant_id/oauth2/v2.0/token",
body: {
multipart: true,
client_id: 'id',
client_secret: 'secret',
scope: 'https://graph.microsoft.com/.default',
grant_type: 'client_credentials'
}
)
```
52 changes: 52 additions & 0 deletions examples/microsoft_graph.rb
@@ -0,0 +1,52 @@
require 'httparty'

class MicrosoftGraph
MS_BASE_URL = "https://login.microsoftonline.com".freeze
TOKEN_REQUEST_PATH = "oauth2/v2.0/token".freeze

def initialize(tenant_id)
@tenant_id = tenant_id
end

# Make a request to the Microsoft Graph API, for instance https://graph.microsoft.com/v1.0/users
def request(url)
return false unless (token = bearer_token)

response = HTTParty.get(
url,
headers: {
Authorization: "Bearer #{token}"
}
)

return false unless response.code == 200

return JSON.parse(response.body)
end

private

# A post to the Microsoft Graph to get a bearer token for the specified tenant. In this example
# our Rails application has already been given permission to request these tokens by the admin of
# the specified tenant_id.
#
# See here for more information https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
#
# This request also makes use of the multipart/form-data post body.
def bearer_token
response = HTTParty.post(
"#{MS_BASE_URL}/#{@tenant_id}/#{TOKEN_REQUEST_PATH}",
body: {
multipart: true,
client_id: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_id],
client_secret: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_secret],
scope: 'https://graph.microsoft.com/.default',
grant_type: 'client_credentials'
}
)

return false unless response.code == 200

JSON.parse(response.body)['access_token']
end
end

0 comments on commit 1615568

Please sign in to comment.