Access OneDrive for Business with PowerShell as an Azure AD App

Marcel Meurer's picture

Some months ago I wrote a blog and a PowerShell module to operate OneDrive (the private one): https://www.sepago.com/blog/2016/02/21/Use-PowerShell-Module-OneDrive-from-PowerShellGallery-command-line. Accessing OneDrive for Business is well documented at https://dev.onedrive.com/, but it is more difficult to authenticate to it than to OneDrive.

These are the steps for the authentication:

Register your PowerShell app in your Azure AD

To allow your PowerShell script to authenticate users you have to register it in Azure Active Directory. In my case I registered the app called “Access-1Drive4Business” in portal.azure.com. The Sign-on-URL is a valid but non existing URL. I chose http://sepago.de/1Drive4Business

 

Now configure the API access with “Required permissions” and add “Office 365 SharePoint Online (Microsoft.Sharepoint)”.

For the Office 365 API check the delegated permissions “Read and write user files“ and “Read user files“.

After this generate a secret key for your PowerShell script and copy this key for later use. Also copy the application GUID.

After this you should have the following data for your PowerShell script:

Application GUID: 2831fc52-e1b8-4493-9f3a-a3dad74b2081

Application Secret Key: TqoSXXXXXXXXXXXXXXXXXXXXXXXXXXXX=

Single-Sign-On URL: http://sepago.de/1Drive4Business

You also need a resource id. For my OneDrive 4 Business account it is: "https://sepagogmbh-my.sharepoint.com/" (the last / is important).

Resource ID: https://sepagogmbh-my.sharepoint.com/

To test the first step of the authentication process, copy this URL into your browser and log in:

https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=< Application GUID>&redirect_uri=< Single-Sign-On URL>

In my case:

https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=2831fc52-e1b8-4493-9f3a-a3dad74b2081&redirect_uri=http://sepago.de/1Drive4Business

Accept access through your application:

After this you will be redirected to your SSO URL with an appended “code” for the further authentication:

Here is my sample PowerShell script to authenticate a user interactively. It shows the files and folders in the root:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$AppID="2831fc52-e1b8-4493-9f3a-a3dad74b2081"		# Application GUID

$AppKey="TqoSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX="	# Application Secret Key

$RedirectURI="http://sepago.de/1Drive4Business"		# Single-Sign-On URL

$ResourceID="https://sepagogmbh-my.sharepoint.com/"	# Resource ID



$form = New-Object Windows.Forms.Form

$form.text = "Authenticate to OneDrive for Business"

$form.size = New-Object Drawing.size @(700,600)

$form.Width = 675

$form.Height = 880

$web = New-object System.Windows.Forms.WebBrowser

$web.IsWebBrowserContextMenuEnabled = $true

$web.Width = 600

$web.Height = 760

$web.Location = "25, 25"

$web.navigate("https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id="+$AppID+"&redirect_uri="+$RedirectURI)

$DocComplete  = {

	$Global:uri = $web.Url.AbsoluteUri

	if ($web.Url.AbsoluteUri -match "code=|error") {$form.Close() }

}

$web.Add_DocumentCompleted($DocComplete)

$form.Controls.Add($web)

$form.showdialog() | out-null

# Build object from last URI (which should contains the token)

$ReturnURI=($web.Url).ToString().Replace("#","&")

$Code = New-Object PSObject

ForEach ($element in $ReturnURI.Split("?")[1].Split("&")) 

{

	$Code | add-member Noteproperty $element.split("=")[0] $element.split("=")[1]

}



if($Code.Code) 

{

    #Code exist

    write-host("Access code:")

    write-host($Code.code)



    #Get authentication token

    $body="client_id="+$AppID+"&redirect_uri="+$RedirectURI+"&client_secret="+$AppKey+"&code="+$Code.code+"&grant_type=authorization_code&resource="+$ResourceID

    $Response = Invoke-WebRequest -Method Post -ContentType "application/x-www-form-urlencoded" "https://login.microsoftonline.com/common/oauth2/token" -body $body

    $Authentication = $Response.Content|ConvertFrom-Json



    if($Authentication.access_token)

    {

        #Authentication token exist

        write-host("`nAuthentication:")

        $Authentication



        #Samples:

        write-host("Drive info:")

        $Response=Invoke-WebRequest -Method GET -Uri ($ResourceID+"_api/v2.0"+"/drive") -Header @{ Authorization = "BEARER "+$Authentication.access_token} -ErrorAction Stop

        $responseObject = ConvertFrom-Json $Response.Content

        $responseObject 



        write-host("Files and folders in root drive:")

        $Response=Invoke-WebRequest -Method GET -Uri ($ResourceID+"_api/v2.0"+"/drive/root/children:") -Header @{ Authorization = "BEARER "+$Authentication.access_token} -ErrorAction Stop

        $responseObject = ($Response.Content|ConvertFrom-Json).value

        $responseObject 







    } else

    {    

        #No Code

        write-host("No authentication token recieved to log in")

    }

} else



{

    #No Code

    write-host("No code received to log in")

}

 

My sample output:

The next step could be an extension of my OneDrive module to support OneDrive for Business.

Comments
(500) Internal Error
Hello Marcel, First of all, thank you for these well-explained tutorials. They are very helpful for a beginner like me. I just have a few remarks. I was stuck for a while on a stupid error, which was that my client_secret was not encoded well in the powershell script. I could retrieve the access token with Postman but not with your powershell app. I just regenerated a key and it worked. I am now stucked on something else: When I try accessing the drive (GET on https://<tenant>-my.sharepoint.com/_api/v2.0/drive/) or the files, I get this error: Invoke-WebRequest : The remote server returned an error: (500) Internal Server Error. $Response=Invoke-WebRequest -Method GET -Uri ($newurl) -Header @{ A ... + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand%. With Postman, I just receive this message: { "error": { "code": "generalException", "message": "An unspecified error has occurred." } }. Could it be that we now have to use the graph api to access OneDrive? Thank you in advance, Victor
Marcel Meurer's picture
(500) Internal Error
Hi Victor. I testet it and I found an error: If you start this script outside the ISE you must add the following line on top (I corrected it in the script above): [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") Can you test it? The script schould generate the code and the access token. Marcel
Add new comment
By submitting this form, you accept the Mollom privacy policy.