Hey there, fellow Ruby enthusiast! Ready to dive into the world of Microsoft Entra ID API integration? You're in for a treat. This guide will walk you through the process of building a robust integration that'll have you managing users, groups, and roles like a pro. Let's get cracking!
Before we jump in, make sure you've got:
First things first – let's get you authenticated:
require 'oauth2' client = OAuth2::Client.new( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, site: 'https://login.microsoftonline.com', token_url: '/YOUR_TENANT_ID/oauth2/v2.0/token' ) token = client.client_credentials.get_token(scope: 'https://graph.microsoft.com/.default')
Let's keep it simple:
mkdir entra_id_integration
cd entra_id_integration
bundle init
Add these to your Gemfile:
gem 'oauth2' gem 'httparty'
Run bundle install
and you're good to go!
Now for the fun part – let's talk to the API:
require 'httparty' class EntraIDClient include HTTParty base_uri 'https://graph.microsoft.com/v1.0' def initialize(token) @options = { headers: { 'Authorization' => "Bearer #{token}" } } end def get_users self.class.get('/users', @options) end # Add more methods as needed end client = EntraIDClient.new(token.token) users = client.get_users puts users
Let's add some CRUD operations:
def create_user(user_data) self.class.post('/users', @options.merge(body: user_data.to_json)) end def update_user(user_id, user_data) self.class.patch("/users/#{user_id}", @options.merge(body: user_data.to_json)) end def delete_user(user_id) self.class.delete("/users/#{user_id}", @options) end def assign_role(user_id, role_id) body = { '@odata.id' => "https://graph.microsoft.com/v1.0/directoryRoles/#{role_id}" } self.class.post("/users/#{user_id}/memberOf/$ref", @options.merge(body: body.to_json)) end
Always expect the unexpected:
def handle_response(response) case response.code when 200..299 response when 429 raise "Rate limit exceeded. Retry after #{response.headers['Retry-After']} seconds" else raise "API error: #{response.code} - #{response.message}" end end
Don't forget to implement proper logging and respect rate limits!
Test, test, and test again:
require 'minitest/autorun' class EntraIDClientTest < Minitest::Test def setup @client = EntraIDClient.new('your_test_token') end def test_get_users response = @client.get_users assert_equal 200, response.code end # Add more tests end
Want to level up? Consider implementing:
And there you have it! You've just built a solid Microsoft Entra ID API integration in Ruby. Remember, this is just the beginning – there's a whole world of possibilities to explore with this API. Keep experimenting, and don't hesitate to dive into the official documentation for more advanced features.
Happy coding, Rubyist! 🚀