Introduction

In this article, we will walk through how to create an Azure AD application that has the necessary permissions to access user data in OneDrive, generate a client secret, and execute a PowerShell script to fetch and report on sharing permissions of OneDrive files.

Steps to Create an Azure AD Application with the Required Permissions

1. Create an Azure AD Application

Follow these steps to register a new Azure AD application in your Microsoft Azure portal:

2. Assign Required Permissions

Now, let's grant the application the permissions it needs to access data in OneDrive:

3. Create a Client Secret

The app will need a client secret to authenticate:

4. Use the Client ID, Tenant ID, and Client Secret in the Script

Now that you have the necessary credentials, you'll be able to authenticate with Azure and Microsoft Graph API in the script.

PowerShell Script for Fetching OneDrive Sharing Report

Below is the PowerShell script that utilizes Microsoft Graph API to gather OneDrive file and folder structures, along with sharing permissions.


# Define your Azure AD app credentials
$clientId = ""
$tenantId = ""
$clientSecret = ""

# Prepare the token request URL for Microsoft Graph API
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Create the request body for obtaining an access token
$body = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $clientSecret
    grant_type    = "client_credentials"
}

# Send the request to get the access token
$response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $response.access_token

# Set the authorization header with the access token
$headers = @{
    Authorization = "Bearer $accessToken"
}

# Function to get the list of users in your tenant
function Get-AllUsers {
    $usersUrl = "https://graph.microsoft.com/v1.0/users"
    $users = Invoke-RestMethod -Uri $usersUrl -Headers $headers
    return $users.value
}

# Function to list all files and folders under each user's OneDrive
function Get-UserFiles {
    param(
        [string]$userId
    )
    
    $driveUrl = "https://graph.microsoft.com/v1.0/users/$userId/drive/root/children"
    $driveItems = Invoke-RestMethod -Uri $driveUrl -Headers $headers
    return $driveItems.value
}

# Function to get sharing details and permissions for each user's files/folders in OneDrive
function Get-SharingPermissions {
    param(
        [string]$userId,
        [string]$fileId
    )
    
    $sharingUrl = "https://graph.microsoft.com/v1.0/users/$userId/drive/items/$fileId/permissions"
    $permissions = Invoke-RestMethod -Uri $sharingUrl -Headers $headers
    return $permissions.value
}

# Initialize an array to hold the output data
$outputData = @()

# Main Execution
$users = Get-AllUsers

foreach ($user in $users) {
    Write-Host $user.displayName
    # Get user's OneDrive files and folders
    $files = Get-UserFiles -userId $user.id
    $files | ForEach-Object {
        $fileName = $_.name
        $fileId = $_.id
        $fileType = $_.file.mimeType

        # For each file, collect data on the file itself
        $fileData = New-Object PSObject -property @{
            UserPrincipalName = $user.userPrincipalName
            FileName          = $fileName
            FileId            = $fileId
            FileType          = $fileType
        }

        # Get sharing permissions for each file
        $permissions = Get-SharingPermissions -userId $user.id -fileId $fileId
        $permissions | ForEach-Object {
            # Collect sharing data for each permission entry
            $sharingData = New-Object PSObject -property @{
                UserPrincipalName = $user.userPrincipalName
                FileName          = $fileName
                SharedWith        = $_.grantedTo.user.email
                Permissions       = $_.roles -join ", "
                SharedLink        = $_.link.webUrl
            }

            # Add sharing data to the output array
            $outputData += $sharingData
        }

        # Add file data to the output array (in case there were no sharing permissions)
        if ($permissions.Count -eq 0) {
            $outputData += $fileData
        }
    }
}

# Define the CSV file path
$csvFilePath = "C:\temp\output.csv"

# Export collected data to CSV
$outputData | Export-Csv -Path $csvFilePath -NoTypeInformation

Write-Host "Script execution completed. Data has been saved to $csvFilePath."
            

Script Overview

Sample Output (CSV)

UserPrincipalName FileName FileId FileType SharedWith Permissions
[email protected] Document1.txt file123 text [email protected] Reader
[email protected] Spreadsheet.xlsx file124 excel [email protected] Contributor
[email protected] Image.png file125 image [email protected] Reader

Final Notes

By following these steps and running the script, you can automate the process of generating a OneDrive sharing report for all users in your Azure AD tenant.