bhimavarapumurali / testAngular

0 stars 0 forks source link

Graphapi #1

Open bhimavarapumurali opened 1 year ago

bhimavarapumurali commented 1 year ago

using Microsoft.Identity.Client; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks;

public class GraphApiClient { private readonly IPublicClientApplication _app; private readonly string _graphApiEndpoint = "https://graph.microsoft.com/v1.0/";

public GraphApiClient(string clientId, string authority)
{
    _app = PublicClientApplicationBuilder
        .Create(clientId)
        .WithAuthority(authority)
        .Build();
}

public async Task<string> AcquireTokenInteractiveAsync(string[] scopes)
{
    var result = await _app.AcquireTokenInteractive(scopes).ExecuteAsync();
    return result.AccessToken;
}

public async Task<string> AcquireTokenOnBehalfOfAsync(string clientId, string clientSecret, string[] scopes, string userAssertion)
{
    var clientCredential = new ClientCredential(clientId, clientSecret);
    var result = await _app.AcquireTokenOnBehalfOf(scopes, clientCredential, new UserAssertion(userAssertion)).ExecuteAsync();
    return result.AccessToken;
}

public async Task<string> CallGraphApiAsync(string accessToken, string apiEndpoint)
{
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        HttpResponseMessage response = await httpClient.GetAsync(_graphApiEndpoint + apiEndpoint);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }
        else
        {
            return null;
        }
    }
}

}

string clientId = "your-client-id"; string authority = "https://login.microsoftonline.com/{tenant-id}"; string[] scopes = new string[] { "User.Read" };

GraphApiClient graphClient = new GraphApiClient(clientId, authority);

// For public client applications string accessToken = await graphClient.AcquireTokenInteractiveAsync(scopes);

// For confidential client applications string clientSecret = "your-client-secret"; string userAssertion = "user-assertion"; string accessToken = await graphClient.AcquireTokenOnBehalfOfAsync(clientId, clientSecret, scopes, userAssertion);

string response = await graphClient.CallGraphApiAsync(accessToken, "me");