How to integrate Graph API in MVC5 application- Implementation

How to integrate Graph API in MVC5 application.

  • Determine the scope of the integration: Decide which aspects of the Graph API you want to integrate into your application, and what actions you want users to be able to perform. For example, you may want to allow users to authenticate with their Microsoft accounts, or you may want to retrieve data from their OneDrive or Outlook accounts.
  • Create a new service: Create a new service within your MVC5 application that will handle the Graph API integration. This service should be responsible for handling all interactions with the Graph API, and should expose methods for performing specific tasks (e.g., retrieving a user's email messages).
  • Add the necessary dependencies: Depending on which aspects of the Graph API you want to use, you may need to add additional dependencies to your application (e.g., the Microsoft Graph SDK). Make sure to follow best practices for managing dependencies in your application.
  • Implement authentication:
The IGraphApiService interface defines a single method GetAuthenticatedGraphClientAsync, which returns an IGraphServiceClient object that has been authenticated with the Graph API.

The GraphApiService class implements this interface and takes in the necessary parameters to authenticate with the Graph API (client ID, client secret, tenant ID, and scopes). It uses the Microsoft Identity Client library to obtain an access token for the Graph API, and then sets up an instance of the GraphServiceClient class with an authentication provider that includes this access token.

Note that this is just one possible implementation of the service, and there may be other approaches depending on the specific requirements of your application.


using Microsoft.Graph;

using Microsoft.Identity.Client;

using System.Threading.Tasks;


public interface IGraphApiService

{

    Task<IGraphServiceClient> GetAuthenticatedGraphClientAsync();

}


public class GraphApiService : IGraphApiService

{

    private readonly string _clientId;

    private readonly string _clientSecret;

    private readonly string _tenantId;

    private readonly string[] _scopes;

    private readonly IConfidentialClientApplication _confidentialClientApplication;


    public GraphApiService(string clientId, string clientSecret, string tenantId, string[] scopes)

    {

        _clientId = clientId;

        _clientSecret = clientSecret;

        _tenantId = tenantId;

        _scopes = scopes;


        _confidentialClientApplication = ConfidentialClientApplicationBuilder

            .Create(_clientId)

            .WithClientSecret(_clientSecret)

            .WithAuthority(new Uri($"https://login.microsoftonline.com/{_tenantId}/v2.0"))

            .Build();

    }


    public async Task<IGraphServiceClient> GetAuthenticatedGraphClientAsync()

    {

        var authResult = await _confidentialClientApplication.AcquireTokenForClient(_scopes).ExecuteAsync();


        var graphClient = new GraphServiceClient(

            new DelegateAuthenticationProvider(requestMessage =>

            {

                requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);


                return Task.FromResult(0);

            }));


        return graphClient;

    }

}

----------------

This method uses the GetAuthenticatedGraphClientAsync method from the GraphApiService class to obtain an authenticated instance of the GraphServiceClient class. It then uses this client to perform a search for users based on the given query.

The Filter method is used to specify the search criteria, which in this case is a string that starts with the query and matches either the user's display name, email address, or user principal name (i.e., their login name). Note that the startswith filter function is used to perform a prefix search on these fields.

Finally, the GetAsync method is called to retrieve the matching users, and the CurrentPage property is used to convert the IGraphServiceUsersCollectionPage object returned by the API to a List<User> object that can be returned by the method.

public async Task<List<User>> SearchUsersAsync(string query)
{
    var graphClient = await GetAuthenticatedGraphClientAsync();

    var users = await graphClient.Users
        .Request()
        .Filter($"startswith(displayName, '{query}') or startswith(mail, '{query}') or startswith(userPrincipalName, '{query}')")
        .GetAsync();

    return users.CurrentPage.ToList();
}

Comments

Popular posts from this blog

Integrating Microsoft Graph API in Your ASP.NET MVC5

Implement graph API in Mvc 5