แก้ไข

แชร์ผ่าน


Build API clients for Ruby with Microsoft identity authentication

In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.

Required tools

Create a project

Create a new file named Gemfile in the root directory of your project.

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

For this tutorial, use the default implementations.

  1. Edit your Gemfile and add the following code.

    source 'https://rubygems.org'
    
    gem "microsoft_kiota_abstractions"
    gem "microsoft_kiota_serialization_json"
    gem "microsoft_kiota_authentication_oauth"
    gem "microsoft_kiota_faraday"
    
  2. To install dependencies, run the following command.

    bundle install
    

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l ruby -d get-me.yml -n Graph -o ./client

Lastly, create a file called graph.rb in the client folder that was created by Kiota. Add the following code:

# frozen_string_literal: true
module Graph
end

Register an application

To be able to authenticate with the Microsoft Entra identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Microsoft Entra admin center.

The following instructions register an app and enable authorization code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Set Redirect URI platform to Web, and set the value to http://localhost.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  6. Copy the Value of the new secret before you leave this page. It is never displayed again. Save the value for later.

Create the client application

Create a file in the root of the project named get_user.rb and add the following code. Replace the client_id and client_secret with your credentials from the previous step.

Use the following steps to get an authorization code.

Important

Authorization codes are short-lived, typically expiring after 10 minutes. You should get a new authorization code just before running the example.

  1. Open your browser and paste in the following URL, replacing YOUR_CLIENT_ID with the client ID of your app registration.

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&response_mode=query&scope=User.Read
    
  2. Sign in with your Microsoft account. Review the requested permissions and grant consent to continue.

  3. Once authentication completes, your browser will redirect to http://localhost. The browser displays an error that can be safely ignored.

  4. Copy the URL from your browser's address bar.

  5. Copy everything in the URL between code= and &. This value is the authorization code.

Replace the auth_code with your authorization code.

# frozen_string_literal: true
require 'microsoft_kiota_serialization_json'
require 'microsoft_kiota_abstractions'
require 'microsoft_kiota_authentication_oauth'
require 'microsoft_kiota_faraday'
require_relative './client/get_user_api_client'

client_id = 'CLIENT_ID'
client_secret = 'CLIENT_SECRET'
auth_code = 'AUTH_CODE'

tenant_id = 'common'
redirect_uri = 'http://localhost'

# The auth provider will only authorize requests to
# the allowed hosts, in this case Microsoft Graph
allowed_hosts = ['graph.microsoft.com']
graph_scopes = ['User.Read']
token_request_context = MicrosoftKiotaAuthenticationOAuth::AuthorizationCodeContext
  .new(tenant_id, client_id, client_secret, redirect_uri, auth_code)

auth_provider = MicrosoftKiotaAuthenticationOAuth::OAuthAuthenticationProvider
  .new(token_request_context, allowed_hosts, graph_scopes)

request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter
  .new(auth_provider,
       MicrosoftKiotaSerializationJson::JsonParseNodeFactory.new,
       MicrosoftKiotaSerializationJson::JsonSerializationWriterFactory.new)

client = GetUser::GetUserApiClient.new(request_adapter)

me = client.me().get().resume

puts "Hi! My name is #{me.display_name}, and my ID is #{me.id}."

Run the application

To start the application, run the following command in your project directory.

ruby ./get_user.rb

See also