Skip to content

Example contribution #2

@coezbek

Description

@coezbek

Hi,
I recently used the microsoft-graph-client gem to add user invitations to our Rails app and would like to contribute as an example for how to do application authorized calls. I hope this helps. You need to replace client_id/secret, tenant_id, redirect_url and the message body with your own data.

    client_id     = Rails.application.credentials.azure[:client_id]
    client_secret = Rails.application.credentials.azure[:client_secret]
    tenant_id     = Rails.application.credentials.azure[:tenant_id]

    authority     = 'login.microsoftonline.com'
    resource      = "https://graph.microsoft.com"

    auth_ctx = ADAL::AuthenticationContext.new(authority, tenant_id)
    client_cred = ADAL::ClientCredential.new(client_id, client_secret)
    result = auth_ctx.acquire_token_for_client(resource, client_cred)

    case result
    when ADAL::SuccessResponse
      #puts 'Successfully authenticated with client credentials. Received access ' \
      #     "token: #{result.access_token}."

      graph = Microsoft::Graph.new(token: result.access_token)

      begin
        find_user = graph.get("/users?$filter=(UserType eq 'Guest') and (mail eq '#{email}')&$select=externalUserState")

        # If user doesn't exist or hasn't accepted the invitation, create a new invitation
        if find_user.value.empty? || find_user.value[0].external_user_state != "Accepted"

          invitation = {
            invitedUserEmailAddress: email,
            inviteRedirectUrl: 'https://$$$$redirect_url$$$$',
            sendInvitationMessage: true,
            invitedUserMessageInfo: {
              customizedMessageBody: "You have been invited to $$$$XYZ$$$$. Please click the link below to accept the invitation and set up your account."
            }
          }

          parsed_response = graph.post("/invitations", body: invitation )

          puts " - Invitation sent to #{email}. Status: #{parsed_response.status}"
        else
          puts " ✓ User #{email} already is registered with tenant"
        end

      rescue Microsoft::Graph::Error => e
        puts e.inspect
        puts e.response.inspect
      end

    when ADAL::FailureResponse
      puts 'Failed to authenticate with client credentials. Received error: ' \
           "#{result.error} and error description: #{result.error_description}."
    end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions