-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGet-SpotifyRefreshToken.ps1
174 lines (160 loc) · 6.14 KB
/
Get-SpotifyRefreshToken.ps1
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
<#
.SYNOPSIS
Obtain Refresh Token from Spotify API using the OAuth 2 client authorization code flow
.DESCRIPTION
This function utilizes a .NET HTTP Listener to parse the Redirect URL containing the Authorization Code
Alternatively, a user can choose to complete the flow interactively by pasting the Redirect URL into the PowerShell session
A Spotify Refresh Token is obtained using the Client Authorization Code and the Spotify Developer Application credentials
.NOTES
https://developer.spotify.com/dashboard
https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
.LINK
https://ryland.dev
#>
[CmdletBinding()]
param (
# Spotify Developer Application Client ID
[Parameter(Mandatory)]
[string] $ClientId,
# Spotify Developer Application Client Secret
[Parameter(Mandatory)]
[string] $ClientSecret,
# Spotify Developer Application Redirect URI
[Parameter(Mandatory)]
[Alias('RedirectUrl')]
[string] $RedirectUri,
# Disable automatic browser opening
[Parameter()]
[switch] $ManualAuth
)
#region Init
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Web
[System.Uri]$RedirectUri = $RedirectUri
$EncodedRedirectUri = [System.Web.HTTPUtility]::UrlEncode($RedirectUri.AbsoluteUri)
# Request only read scopes
$ApiScopes = @(
'playlist-read-collaborative',
'playlist-read-private',
'user-follow-read',
'user-library-read',
'user-read-email',
'user-read-private',
'user-read-recently-played',
'user-top-read'
) -join '%20'
$AuthState = (New-Guid).ToString()
$AuthCodeUri = "https://accounts.spotify.com/authorize?client_id=$ClientId&response_type=code&redirect_uri=$EncodedRedirectUri&state=$AuthState&scope=$ApiScopes"
$TokenUri = 'https://accounts.spotify.com/api/token'
#endregion Init
#region StartListener
if ($ManualAuth) {
$HttpListenerReady = $false
} else {
$RedirectPrefix = "$($RedirectUri.Scheme)://$($RedirectUri.Authority)/"
$HttpListener = New-Object System.Net.HttpListener
$HttpListener.Prefixes.Add($RedirectPrefix)
$HttpListener.Start()
if ($HttpListener.IsListening) {
Write-Verbose 'HTTP Listener is ready'
$HttpListenerReady = $true
} else {
Write-Warning 'HTTP Listener is not ready. Using ManualAuth method'
$HttpListenerReady = $false
$HttpListener.Stop()
$ManualAuth = $true
}
}
#endregion StartListener
#region OpenBrowser
if ($ManualAuth) {
Write-Output "[INFO] Navigate to the following URL in a web browser:`n$AuthCodeUri"
} else {
try {
if ($IsMacOS) {
Write-Output '[INFO] Opening MacOS default browser for user login'
Invoke-Expression 'open -u "$AuthCodeUri"'
} elseif ($IsLinux) {
Write-Output '[INFO] Opening Linux default browser for user login (requires a freedesktop.org compliant desktop)'
Start-Process xdg-open $AuthCodeUri
} else {
Write-Output '[INFO] Opening Windows default browser for user login'
Invoke-Expression "rundll32 url.dll, FileProtocolHandler '$AuthCodeUri'"
}
} catch {
Write-Verbose 'Stop HTTP Listener'
$HttpListener.Stop()
Write-Error "Error opening default browser for user login: $_"
}
}
#endregion OpenBrowser
#region GetAuthCode
if ($HttpListenerReady) {
Write-Output '[INFO] Please complete browser login within 60 seconds'
$Context = $null
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
try {
while ($HttpListener.IsListening -and $Stopwatch.Elapsed -lt [TimeSpan]::ParseExact('01', 'mm', $null)) {
if ($null -eq $Context) {
$Context = $HttpListener.GetContextAsync()
}
if ($Context.IsCompleted) {
$Result = $Context.Result
$Context = $null
$AuthResponseUri = $Result.Request.Url
$ContextResponse = $Result.Response
$BrowserDialog = [System.Text.Encoding]::UTF8.GetBytes('Login complete. You may now close this window.')
$ContextResponse.ContentLength64 = $BrowserDialog.Length
$ContextResponse.OutputStream.Write($BrowserDialog, 0, $BrowserDialog.Length)
$ContextResponse.OutputStream.Close()
$Stopwatch.Stop()
break
}
}
} catch {
Write-Error "Error while listening for browser Response: $_"
} finally {
Write-Verbose 'Stop HTTP Listener'
$HttpListener.Stop()
}
} else {
$AuthResponseUri = Read-Host 'Paste the entire URL you are redirected to'
$AuthResponseUri = [System.Uri]$AuthResponseUri
}
#endregion GetAuthCode
#region ValidateAuthCode
$AuthResponseQueryString = [System.Web.HttpUtility]::ParseQueryString($AuthResponseUri.Query)
if ([string]::IsNullOrEmpty($AuthResponseUri.OriginalString)) {
Write-Error 'Response cannot be empty'
}
if ($AuthResponseQueryString['state'] -ne $AuthState) {
Write-Error "Response state [$($AuthResponseQueryString['state'])] does not match the request state [$AuthState]"
}
if ($AuthResponseQueryString['error']) {
Write-Error "Response contains an error: $($AuthResponseQueryString.Error)"
}
if ($AuthResponseQueryString['code']) {
Write-Verbose 'Received Authorization Code for user'
$AuthCode = $AuthResponseQueryString['code']
} else {
Write-Error 'Response does not contain an Authorization Code'
}
#endregion ValidateAuthCode
#region GetRefreshToken
$TokenBody = @{
grant_type = 'authorization_code'
code = $AuthCode
redirect_uri = $RedirectUri
client_id = $ClientId
client_secret = $ClientSecret
}
try {
Write-Verbose 'Request Spotify API Refresh Token using Authorization Code and Application credentials'
$TokenResponse = Invoke-RestMethod -Method Post -Uri $TokenUri -Body $TokenBody
} catch {
Write-Error "Error obtaining Refresh Token from Spotify API: $_"
}
Write-Output '*****Spotify Refresh Token*****'
Write-Output $TokenResponse.refresh_token
Write-Output '*******************************'
#endregion GetRefreshToken