| | 0

Access OneDrive for Business with PowerShell as an Azure AD App

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
[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"
$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.