PowerShell automation with OAuth2

Hi,

I have quite a bit of code working with OAuth2 authenticating. (Got help from this post: https://blogs.technet.microsoft.com/ronba/2016/05/09/using-powershell-and-the-office-365-rest-api-with-oauth/)

The only issue I have now is, I don’t know how to really ‘automate’ this script, because it requires me to manually enter the username and password.

Any advice?

The OAuth Window

Function Show-OAuth2Window {
[cmdletbinding()]
param(
[System.Uri]$Url
)

Add-Type -AssemblyName System.Windows.Forms

$form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=440;Height=640}
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=420;Height=600;Url=($url ) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
if ($Global:Uri -match "error=[^&]*|code=[^&]*") {$form.Close() }
}
$web.ScriptErrorsSuppressed = $true
$web.Add_DocumentCompleted($DocComp)
$form.Controls.Add($web)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog() | Out-Null
$queryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Url.Query)
$output = @{}
foreach($key in $queryOutput.Keys){
$output["$key"] = $queryOutput[$key]
}

Write-Output $output
Write-Verbose $($web.Url.Query)
}
Getting the Authorization Code
Function Get-OAuth2Authorization {
<#
.SYNOPSIS
Gets OAuth2 Authorization code

#>
[cmdletbinding()]
Param (
$AuthPage = 'https://app.teamleader.eu/oauth2/authorize',
$RedirectUrl,
$ClientId = 'f60925cc3929a3af4c6bcc9dabebc65e',
$ClientSecret = 'c1b28e24830b9f98bd6bd3b628264996'

)

# Start login
Add-Type -AssemblyName System.Web
$loginUrl = "$AuthPage?response_type=code&redirect_uri=” + [System.Web.HttpUtility]::UrlEncode($redirectUrl) + “&client_id=$clientid” Try { $queryOutput = Show-OAuth2Window -Url $loginUrl -Verbose $AuthCode = $queryOutput.code`

#This is your authcode
Return $AuthCode
} Catch {
Write-error $_
}

}

Using the Authorization Code to Get Tokens
Function Get-OAuth2Token {
[cmdletbinding()]
Param (
$Uri =
$RedirectUrl,
$clientid,
$clientSecret,
$AuthCode,
$Refreshtoken
)
If ( !$RefreshToken ) {

$PostRequest = @{
grant_type = 'authorization_code'
redirect_uri = $redirectUrl
client_id = $ClientId
client_secret = [System.Web.HttpUtility]::UrlEncode($ClientSecret)
code = $AuthCode
}
} Else {
$PostRequest = @{
grant_type = 'refresh_token'
client_id = $ClientId
client_secret = [System.Web.HttpUtility]::UrlEncode($ClientSecret)
refresh_token = $Refreshtoken
}

}

Try {
$result = Invoke-RestMethod -Method Post -ContentType application/x-www-form-urlencoded -Uri $FromUri -Body $PostRequest

$Timestamp = $(Get-date)
Write-Output @{
Timestamp = $Timestamp
ExpiresIn = $Result.Expires_in
AccessToken = $Result.access_token
RefreshToken = $Result.refresh_token
}
} Catch {
Write-Error "Error occured while using: Postrequestn $($Postrequest | Out-string)” Write-Error $_ }`

}

submitted by /u/mieeel
[link] [comments]

Leave a Reply