Modules/OAuth.psm1

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
Add-Type -AssemblyName System.Web
function Get-AuthorizationCode {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [string]
        $AuthorizationEndpoint,

        [parameter(Mandatory)]
        [pscredential]
        $ClientIdSecret,

        [parameter(Mandatory)]
        [string[]]
        $Permissions = "-",

        [parameter(Mandatory)]
        [string]
        $RedirectUri
    )

    begin {
        $redirectUriEncoded = [System.Web.HttpUtility]::UrlEncode($redirectUri)
    }

    process {
        [void]$(
            $url = [string]::Format("{0}?response_type=code&redirect_uri={1}&client_id={2}&scope={3}", `
                    $AuthorizationEndpoint, `
                    $redirectUriEncoded, `
                    $ClientIdSecret.UserName, `
                ($Permissions -join '%20'))

            $AuthCode = New-OAuthConfirmationWindow -Url $url

            $PSCmdlet.WriteObject($AuthCode)
        )
    }
}
function Get-AccessToken {
    [cmdletbinding(DefaultParameterSetName = "AuthCode")]
    param(
        [parameter(Mandatory)]
        [string]
        $TokenEndpoint,

        [parameter(Mandatory)]
        [pscredential]
        $ClientIdSecret,

        [parameter(Mandatory, ParameterSetName = "RefreshToken")]
        [string]
        $RefreshToken,

        [parameter(Mandatory, ParameterSetName = "AuthCode")]
        [string]
        $AuthorizationCode,

        [parameter(Mandatory, ParameterSetName = "AuthCode")]
        [string]
        $RedirectUri
    )
    process {
        [void]$(
            $Body = ""

            if ($PSBoundParameters.ContainsKey("RefreshToken")) {
                $GrantType = "refresh_token"

                $Body = "grant_type=$GrantType&refresh_token=$RefreshToken"
            }
            else {
                $GrantType = "authorization_code"
                $redirectUriEncoded = [System.Web.HttpUtility]::UrlEncode($redirectUri)

                $Body = "grant_type=$GrantType&redirect_uri=$redirectUriEncoded&code=$AuthorizationCode"
            }
            $body += [string]::format("&client_id={0}&client_secret={1}", `
                    $ClientIdSecret.UserName, `
                    [System.Web.HttpUtility]::UrlEncode($ClientIdSecret.GetNetworkCredential().Password)
            )

            $Authorization = Invoke-RestMethod -Uri $TokenEndpoint `
                -Method Post -ContentType "application/x-www-form-urlencoded" `
                -Body $body `
                -ErrorAction STOP

            $PSCmdlet.WriteObject($Authorization)
        )
    }
}
function New-OAuthConfirmationWindow {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [string]
        $Url
    )
    [void]$(
        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 = {
            $ReturnUrl = $web.Url.AbsoluteUri
            if ($ReturnUrl -match "error=[^&]*|code=[^&]*") {
                $form.Close()
            }
        }

        $web.ScriptErrorsSuppressed = $true
        $web.Add_DocumentCompleted($DocComp)
        $form.Controls.Add($web)
        $form.Add_Shown( {$form.Activate()})
        $form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterParent
        $form.ShowDialog()

        $queryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Url.Query)

        $output = @{}

        foreach ($key in $queryOutput.Keys) {
            $output["$key"] = $queryOutput[$key]
        }

        $PSCmdlet.WriteObject($output["Code"])
    )
}