Connecting WordPress plugin to active directory (Microsoft AD)

Connecting a WordPress plugin to Microsoft Active Directory involves writing code to perform a HTTP POST to a Microsoft authentication endpoint.

I have put the code for doing this in PHP below and once you have copied this into your plugin you can use the code to retrieve an access token for use in making future API calls to Microsoft hosted resources.

class TC_AD_Service {
	static function getAccessToken($tenant_id, $client_id, $client_secret) {
    $client = new GuzzleHttp\Client();
    $url = '' . $tenant_id . '/oauth2/v2.0/token';
    $response = $client->request('POST', $url, [
      'verify' => false,
      'form_params' => [
        'grant_type' => 'client_credentials',
        'client_id' => $client_id,
        'scope' => '',
        'client_secret' => $client_secret        
    $body = $response->getBody();
    return json_decode($body);

I have made use of the GuzzleHttp library which is a PHP library for making HTTP calls. The library was imported using composer and I use the library to submit a HTTP post to the endpoint.

The URL I used consists of the tenant id which is id of an application registered in Microsoft Active Directory and the Microsoft endpoint to request an OAuth token.

I pass to the endpoint the client id and client secret which I configured in Active Directory along with the powerbi scope.

Finally I return back a PHP object read from the response body and containing the access token and the access token expiry date.