Create a Microsoft Graph service on Rails

Allow create outlook events, teams links, user and events sinchronizations

Posted on November 29, 2024
Azure is the most common directory manager to many companies, so is really important to any SASS app to connect with Azure API (Microsoft Graph), in this post we'll cover how to retrieve data and create events on Azure using Microsft Graph API.

All these scenarios are considered as a separate feature to get and add data or if your SASS is using SSO with Azure(Integrate SSO With Azure)


Understand Microsoft Graph Consumption


One of the first steps to consuming Microsoft Graph API is to get 3 required fields to integrate your app, once you have added your app the Azure Active Directory(here) with Microsoft Graph:
  • Tenant ID
  • Client ID
  • Client Secret
These fields are required to retrieve or send data to Microsoft Graph, what are they for:

  • Tenant ID: it is the Active Directory identification 
  • Client ID: It is the Enterprise Application Identification added on your Active Directory
  • Client Secret: It is the access key to Microsoft Graph API with the current Tenant and Client
Once we have those fields the next step is to assign permission to out app to allow request data, you can find all the necessary documentation here

Create your own Microsoft Graph Class Library


Why create your own Microsoft Graph class? Microsoft has a package to connect to any language, but there's no version for Ruby, so you must choose to wait for a release of the Microsoft package or build a new one for your app. The next step is to define the authentication and methods to retrieve data.

Microsoft offers the authentication method of retrieving data using an app access token or using the current user to get a user access token. In this scenario, we will use the first approach, which is to retrieve data using an app access token, so our first method must be to retrieve the app access token.

App Access Token


require 'http'

class MicrosoftGraph
  BASE_GRAPH_URL = 'https://graph.microsoft.com/v1.0'
  ENDPOINT_TOKEN = '/oauth2/v2.0/token'
  DEFAULT_APP_SCOPE = 'https://graph.microsoft.com/.default offline_access'
  BASE_USER_URL = 'users'
  BASE_CALENDARS_URL = 'calendars'
  BASE_CALENDAR_URL = 'calendar'
  BASE_EVENTS_URL= 'events'
  BASE_GROUPS_URL='/groups'
  TYPE_GET = 0
  TYPE_POST = 1
  TYPE_DELETE = 2
  TYPE_PATCH = 3
 
  def initialize(tenant_id, client_id, client_secret = '')
    @tenant_id = tenant_id
    @client_id = client_id
    @client_secret = client_secret
    @access_token = ''
    @app_access_token = ''
    @keys_uri = ''
  end

  def app_access_token
    path = "#{@tenant}#{ENDPOINT_TOKEN}"
    form_object = {
      client_id: @client_id,
      grant_type: 'client_credentials',
      client_secret: @client_secret,
      scope: DEFAULT_APP_SCOPE,
    }
    response = made_call(path, form_object, TYPE_POST)
    token = ''
    if response.status.code == OK_STATUS
      json_response = JSON.parse(response.body.to_s)
      token = json_response['access_token']
      @app_access_token = token
    end
    token
  end

  def made_call(path, form_object, type)
    if type == TYPE_GET
      HTTP.headers('Content-Type': 'application/x-www-form-urlencoded') 
        .get(path, form: form_object)
    else
      HTTP.headers('Content-Type': 'application/x-www-form-urlencoded') 
        .post(path, form: form_object)
    end
  end
end
Once you retrieve the access token you receive a response with the token value:

According to Microsoft docs the app access token is valid for 1 hour, once we have that access token we must used to request any API request on the headers.


  def graph_call(path, json_object, type)
    case type
    when TYPE_GET
      HTTP.headers('Content-Type': 'application/json', 'Authorization': "Bearer #{@app_access_token}") 
        .get(path, json: json_object)
    when TYPE_POST
      HTTP.headers('Content-Type': 'application/json', 'Authorization': "Bearer #{@app_access_token}") 
        .post(path, json: json_object)
    when TYPE_DELETE
      HTTP.headers('Content-Type': 'application/json', 'Authorization': "Bearer #{@app_access_token}") 
        .delete(path, json: json_object)
    when TYPE_PATCH
      HTTP.headers('Content-Type': 'application/json', 'Authorization': "Bearer #{@app_access_token}") 
        .patch(path, json: json_object)
    end
  end

Get users and user profile

If your Active Directory administrator assign permission to your app to get the list of users, is possible retrieve the list of user and search users' profile

  def users
    path = "#{BASE_GRAPH_URL}/#{BASE_USER_URL}"
    response = graph_call(path, {}, TYPE_GET)
    users = []
    if response.status.code == OK_STATUS
      json_response = JSON.parse(response.body.to_s)
      users = json_response['value']
    end
    users
  end
Now you can create a list of users or assign the Microsoft Graph ID to any existing users on your Rails app.
 [
        {
            "businessPhones": [],
            "displayName": "Conf Room Adams",
            "givenName": null,
            "jobTitle": null,
            "mail": "Adams@contoso.com",
            "mobilePhone": null,
            "officeLocation": null,
            "preferredLanguage": null,
            "surname": null,
            "userPrincipalName": "Adams@contoso.com",
            "id": "6ea91a8d-e32e-41a1-b7bd-d2d185eed0e0"
        },
        {
            "businessPhones": [
                "425-555-0100"
            ],
            "displayName": "MOD Administrator",
            "givenName": "MOD",
            "jobTitle": null,
            "mail": null,
            "mobilePhone": "425-555-0101",
            "officeLocation": null,
            "preferredLanguage": "en-US",
            "surname": "Administrator",
            "userPrincipalName": "admin@contoso.com",
            "id": "4562bcc8-c436-4f95-b7c0-4f8ce89dca5e"
        }]

Get user calendars

Following the Microsoft Graph documentation to access user calendar you must request permissions (Calendars.ReadBasic, Calendars.Read, Calendars.ReadWrite), once the permissions are authorized by the Active Directory administrator we can access the API to create events on Outlook Calendar.


  def calendars(graph_user_id)
   path = "#{BASE_GRAPH_URL}/#{BASE_USER_URL}/#{graph_user_id}/#{BASE_CALENDARS_URL}"
   response = graph_call(path, {}, TYPE_GET)
   calendars = []
   if response.status.code == OK_STATUS
      json_response = JSON.parse(response.body.to_s)
      calendars = json_response['value']
   end
   calendars
  end

  def calendar(graph_user_id)
   path = "#{BASE_GRAPH_URL}/#{BASE_USER_URL}/#{graph_user_id}/#{BASE_CALENDAR_URL}"
   response = graph_call(path, {}, TYPE_GET)
   calendar = {}
   if response.status.code == OK_STATUS
      json_response = JSON.parse(response.body.to_s)
      calendar = json_response
   end
   calendar
  end

 


Create and get events and virtual links

The main purpose of using the Microsoft Graph API is to integrate our Rails app with Microsoft Products like Microsoft Team, Outlook, or Calendar, so our first step is to create a event on Outlook Calendar, once we have the Microsoft identificator of the users on the Active Directory.

The method to retrieve the list of events we need the user id and the calendar id

 def events(graph_user_id, graph_calendar_id)
   path = "#{BASE_GRAPH_URL}/#{BASE_USER_URL}/#{graph_user_id}/#{BASE_CALENDARS_URL}/#{graph_calendar_id}/#{BASE_EVENTS_URL}"
   response = graph_call(path, {}, TYPE_GET)
   events = []
   if response.status.code == OK_STATUS
      json_response = JSON.parse(response.body.to_s)
      events = json_response['value']
   end
   events
end

 Similar to retrieving the list of events to create an event we need the Microsoft user id and the Calendar Id


  def create_event(graph_user_id, graph_calendar_id, event_object) 
    path = "#{BASE_GRAPH_URL}/#{BASE_USER_URL}/#{graph_user_id}/#{BASE_CALENDARS_URL}/#{graph_calendar_id}/#{BASE_EVENTS_URL}"
    response = graph_call(path, json_event_object(event_object), TYPE_POST)
    event = {}
    if response.status.code == CREATED_STATUS
      json_response = JSON.parse(response.body.to_s)
      event = json_response
    end
    event
  end