DNS hijacking (Prevention) Guide 7 Create MS365 API

  • This topic is empty.
  • Post
    Weekend Wiki
    Keymaster
    To interact with Microsoft 365 Exchange via API, you can use the Microsoft Graph API. This API allows you to access data such as emails, calendars, and contacts in Exchange Online. Below is an example of how you can create a basic PHP API to send an email via Microsoft Graph:

    1. Set Up Microsoft Graph API

    You need to register your app in Azure Active Directory and get the Client ID, Client Secret, and Tenant ID.

    2. PHP Script for Sending Email via Microsoft Graph API

    <?php
    // Microsoft Graph API credentials
    $client_id = 'your-client-id';
    $client_secret = 'your-client-secret';
    $tenant_id = 'your-tenant-id';
    $access_token = get_access_token($client_id, $client_secret, $tenant_id);
    
    // Send an email via Microsoft Graph
    function send_email($access_token, $to, $subject, $body) {
        $url = 'https://graph.microsoft.com/v1.0/me/sendMail';
        $data = [
            "message" => [
                "subject" => $subject,
                "body" => [
                    "contentType" => "Text",
                    "content" => $body
                ],
                "toRecipients" => [
                    [
                        "emailAddress" => [
                            "address" => $to
                        ]
                    ]
                ]
            ]
        ];
    
        $options = [
            'http' => [
                'header' => "Content-Type: application/json\r\nAuthorization: Bearer $access_token",
                'method' => 'POST',
                'content' => json_encode($data)
            ]
        ];
    
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        return $response;
    }
    
    // Function to get access token using OAuth2
    function get_access_token($client_id, $client_secret, $tenant_id) {
        $url = "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token";
        $data = [
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'scope' => 'https://graph.microsoft.com/.default'
        ];
    
        $options = [
            'http' => [
                'header' => "Content-Type: application/x-www-form-urlencoded",
                'method' => 'POST',
                'content' => http_build_query($data)
            ]
        ];
    
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        $json_response = json_decode($response, true);
        return $json_response['access_token'];
    }
    
    // Example Usage
    $to = '[email protected]';
    $subject = 'Test Email';
    $body = 'This is a test email sent using Microsoft Graph API';
    echo send_email($access_token, $to, $subject, $body);
    ?>
    

    3. Steps to Set Up:

    1. Register Application in Azure AD to get the Client ID, Client Secret, and Tenant ID.
    2. Grant Permissions for the application (Mail.Send) in the Azure AD portal.
    3. Use the OAuth2 client credentials flow to authenticate and get an Access Token.
    4. Use the Microsoft Graph API to send emails or interact with Exchange Online.

    Key API Endpoints:

    • Send Email: POST https://graph.microsoft.com/v1.0/me/sendMail
    • Read Emails: GET https://graph.microsoft.com/v1.0/me/messages
    • Manage Contacts: GET https://graph.microsoft.com/v1.0/me/contacts

    This script is a starting point to integrate with Microsoft 365 Exchange via API for basic tasks like sending emails. Ensure you handle error checking and secure authentication processes in a production environment.

    To implement a proper tool for interacting with Microsoft 365 Exchange using PHP, here’s a more refined approach, which includes:

    1. OAuth2 Authentication for securely obtaining the access token.
    2. Error handling to ensure smooth operation.
    3. Modular methods for different functionalities (e.g., sending an email, reading messages).

    Final PHP Tool for Microsoft 365 Exchange:

    1. PHP Script for Sending Email via Microsoft Graph API

    <?php
    
    // Required credentials from Azure AD
    $client_id = 'your-client-id';
    $client_secret = 'your-client-secret';
    $tenant_id = 'your-tenant-id';
    $scopes = 'https://graph.microsoft.com/.default';
    
    // Function to get access token via OAuth2
    function get_access_token($client_id, $client_secret, $tenant_id, $scopes) {
        $url = "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token";
        $data = [
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'scope' => $scopes
        ];
    
        // Initialize cURL for the token request
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_HEADER, false);
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            return "Error: " . curl_error($ch);
        }
        
        curl_close($ch);
    
        $json_response = json_decode($response, true);
        return $json_response['access_token'];
    }
    
    // Function to send email using Graph API
    function send_email($access_token, $to, $subject, $body) {
        $url = 'https://graph.microsoft.com/v1.0/me/sendMail';
        
        // Prepare email data
        $data = [
            "message" => [
                "subject" => $subject,
                "body" => [
                    "contentType" => "Text",
                    "content" => $body
                ],
                "toRecipients" => [
                    [
                        "emailAddress" => [
                            "address" => $to
                        ]
                    ]
                ]
            ]
        ];
    
        // Initialize cURL for sending the email
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $access_token",
            "Content-Type: application/json"
        ]);
    
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            return "Error: " . curl_error($ch);
        }
    
        curl_close($ch);
        return $response;
    }
    
    // Example usage: Send an email
    $access_token = get_access_token($client_id, $client_secret, $tenant_id, $scopes);
    $to = '[email protected]';
    $subject = 'Test Email via Microsoft Graph API';
    $body = 'This email is sent using PHP and Microsoft Graph API.';
    $response = send_email($access_token, $to, $subject, $body);
    
    echo $response; // Output response for confirmation
    ?>
    

    Steps to Set Up:

    1. Register the application in the Azure Active Directory and note the Client ID, Client Secret, and Tenant ID.
    2. Grant API permissions (e.g., Mail.Send, Mail.Read) in Azure AD for the app.
    3. Implement OAuth2 to get the access token needed to authenticate API requests.
    4. The script will send a text-based email using the Microsoft Graph API.

    Key Considerations:

    • Use cURL for sending HTTP requests to Microsoft Graph API.
    • Error handling ensures smooth operation when an API call fails.
    • Secure storage for sensitive data like the client_secret is crucial, use environment variables or a secure vault.

    Final Notes:

    This script offers a simple implementation, but for production environments, you’ll need to implement robust error handling, logging, and token refresh mechanisms. Always secure sensitive credentials and never hardcode them directly into the code.

  • You must be logged in to reply to this topic.
en_USEnglish