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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use base64;
use getrandom;
use json;
use open;
use querystring::{querify, stringify};
use random_string;
use reqwest;
use sha2::{Digest, Sha256};
use std::{
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
};
use urlencoding::encode;
const AUTHORIZATION_SUCCESSFUL_HTML: &str = r###"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Success</title>
</head>
<body>
<h1>Success!</h1>
<p>Thank you for authenticating with Spotify! You can close this page now.</p>
</body>
</html>"###;
pub fn generate_verifier() -> (String, String) {
let mut buf = [0u8; 32]; getrandom::getrandom(&mut buf).unwrap(); let code_verifier = base64::encode_config(buf, base64::URL_SAFE).replace("=", ""); let mut code_challenge_hasher = Sha256::new(); code_challenge_hasher.update(&code_verifier); let code_challenge_raw = code_challenge_hasher.finalize(); let code_challenge =
base64::encode_config(code_challenge_raw, base64::URL_SAFE).replace("=", ""); (code_verifier, code_challenge)
}
pub fn get_authorization_code(
client_id: &str,
localhost_port: &str,
redirect_uri: &str,
scope: &str,
code_challenge: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let authorization_code_endpoint = "https://accounts.spotify.com/authorize?".to_owned(); let character_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let state = random_string::generate(16, character_set); let encoded_redirect_uri = encode(&redirect_uri).into_owned(); let parameters = vec![
("response_type", "code"),
("client_id", client_id),
("redirect_uri", &encoded_redirect_uri),
("scope", scope),
("show_dialog", "true"),
("state", &state),
("code_challenge", code_challenge),
("code_challenge_method", "S256"),
];
let query_parameters = stringify(parameters); let auth_url = authorization_code_endpoint + &query_parameters; match open::that(auth_url) {
Ok(()) => println!("Opened authorization url in browser"),
Err(e) => panic!("Failed to open authorization url in browser: {}", e), }
return listen_for_auth_code(localhost_port, &state);
}
fn listen_for_auth_code(port: &str, state: &str) -> Result<String, Box<dyn std::error::Error>> {
let listener = TcpListener::bind(String::from("127.0.0.1:") + &port).unwrap(); for stream in listener.incoming() {
let stream = stream.unwrap();
let auth_code = handle_connection(stream, &state); match auth_code {
Some(result) => match result {
Ok(code) => return Ok(code),
Err(e) => return Err(e),
},
None => continue,
}
}
Err("Failed to find authorization code.".into())
}
fn handle_connection(
mut stream: TcpStream,
state: &str,
) -> Option<Result<String, Box<dyn std::error::Error>>> {
let buf_reader = BufReader::new(&mut stream);
let http_request = buf_reader.lines().next().unwrap().unwrap(); let http_request_len = http_request.len(); if &http_request[0..13] == "GET /callback"
&& &http_request[(http_request_len - 9)..] == " HTTP/1.1"
{
let query = querify(&http_request[14..http_request_len - 9]); if query[1].0 == "state" && query[1].1 == state {
if query[0].0 == "code" {
let authorization_code = String::from(query[0].1); let status_line = "HTTP/1.1 200 OK"; let contents = AUTHORIZATION_SUCCESSFUL_HTML.to_string(); let content_length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {content_length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap(); return Some(Ok(authorization_code)); } else if query[0].0 == "error" {
return Some(Err(format!("Authorization error: {}", query[0].1).into()));
} else {
return Some(Err("Authorization error".into())); }
} else {
return Some(Err(format!(
"Invalid state. Expected {} got {}. Authorization failed",
state, query[1].1
)
.into())); }
} else {
return None; }
}
pub fn get_access_token(
authorization_code: &str,
client_id: &str,
code_verifier: &str,
redirect_uri: &str,
) -> Result<(String, String, i64), Box<dyn std::error::Error>> {
let request_uri = "https://accounts.spotify.com/api/token?"; let client = reqwest::blocking::Client::new();
let encoded_redirect_uri = encode(&redirect_uri).into_owned(); let query_parameters = vec![
("grant_type", "authorization_code"),
("code", authorization_code),
("redirect_uri", &encoded_redirect_uri),
("client_id", client_id),
("code_verifier", code_verifier),
];
let query_string = stringify(query_parameters); let response = client
.post(String::from(request_uri) + &query_string)
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Length", "0") .send()?; if response.status().is_success() {
let response_body = json::parse(&response.text().unwrap()).unwrap(); let access_token = response_body["access_token"].to_string(); let refresh_token = response_body["refresh_token"].to_string(); let expires_in_str = response_body["expires_in"].to_string(); let expires_in: i64 = expires_in_str.parse().unwrap(); return Ok((access_token, refresh_token, expires_in)); } else {
return Err(format!("Error: {}", response.status()).into()); }
}
pub fn refresh_access_token(
refresh_token: &str,
client_id: &str,
) -> Result<(String, i64, String), Box<dyn std::error::Error>> {
let request_uri = "https://accounts.spotify.com/api/token?"; let client = reqwest::blocking::Client::new();
let query_parameters = vec![
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id),
];
let query_string = stringify(query_parameters); let response = client
.post(String::from(request_uri) + &query_string)
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Length", "0") .send()?; if response.status().is_success() {
let response_body = json::parse(&response.text().unwrap()).unwrap(); let access_token = response_body["access_token"].to_string(); let expires_in_str = response_body["expires_in"].to_string(); let expires_in: i64 = expires_in_str.parse().unwrap(); let new_refresh_token = match response_body["refresh_token"] { json::JsonValue::Null => refresh_token.to_string(),
_ => response_body["refresh_token"].to_string(),
};
return Ok((access_token, expires_in, new_refresh_token)); } else {
return Err(format!("Error: {}", response.status()).into()); }
}