mirror of
https://github.com/librespot-org/librespot.git
synced 2025-10-05 19:42:03 +02:00
OAuth process made by a struct, allowing customization options. (#1462)
* get refresh token. Optional auth url browser opening * changelog * access token accepts custom message * docs updated * CustomParams renamed * OAuthToken can be cloned * builder pattern on token management * changelog * docs and format issues * split methods and finish documentation * new example and minor adjustments * typo * remove unnecessary dependency * requested changes * Update oauth/src/lib.rs Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> * Update oauth/src/lib.rs Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> * Update CHANGELOG.md Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> * Update oauth/src/lib.rs Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> * Update oauth/src/lib.rs Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> * Update oauth/src/lib.rs Co-authored-by: Nick Steel <nick@nsteel.co.uk> * Update oauth/src/lib.rs Co-authored-by: Nick Steel <nick@nsteel.co.uk> * remove veil. Oauth flow fix * debug trait instead of veil * Update main.rs Co-authored-by: Nick Steel <nick@nsteel.co.uk> --------- Co-authored-by: Felix Prillwitz <photovoltex@mailbox.org> Co-authored-by: Nick Steel <nick@nsteel.co.uk>
This commit is contained in:
parent
581c8d61ea
commit
f497806fb1
8 changed files with 471 additions and 53 deletions
277
oauth/src/lib.rs
277
oauth/src/lib.rs
|
@ -1,3 +1,4 @@
|
|||
#![warn(missing_docs)]
|
||||
//! Provides a Spotify access token using the OAuth authorization code flow
|
||||
//! with PKCE.
|
||||
//!
|
||||
|
@ -11,66 +12,108 @@
|
|||
//! is appropriate for headless systems.
|
||||
|
||||
use log::{error, info, trace};
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::basic::BasicTokenType;
|
||||
use oauth2::reqwest::{async_http_client, http_client};
|
||||
use oauth2::{
|
||||
basic::BasicClient, AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge,
|
||||
RedirectUrl, Scope, TokenResponse, TokenUrl,
|
||||
};
|
||||
use oauth2::{EmptyExtraTokenFields, PkceCodeVerifier, RefreshToken, StandardTokenResponse};
|
||||
use std::io;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{SocketAddr, TcpListener},
|
||||
sync::mpsc,
|
||||
};
|
||||
use thiserror::Error;
|
||||
use url::Url;
|
||||
|
||||
/// Possible errors encountered during the OAuth authentication flow.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum OAuthError {
|
||||
/// The redirect URI cannot be parsed as a valid URL.
|
||||
#[error("Unable to parse redirect URI {uri} ({e})")]
|
||||
AuthCodeBadUri { uri: String, e: url::ParseError },
|
||||
AuthCodeBadUri {
|
||||
/// Auth URI.
|
||||
uri: String,
|
||||
/// Inner error code.
|
||||
e: url::ParseError,
|
||||
},
|
||||
|
||||
/// The authorization code parameter is missing in the redirect URI.
|
||||
#[error("Auth code param not found in URI {uri}")]
|
||||
AuthCodeNotFound { uri: String },
|
||||
AuthCodeNotFound {
|
||||
/// Auth URI.
|
||||
uri: String,
|
||||
},
|
||||
|
||||
/// Failed to read input from standard input when manually collecting auth code.
|
||||
#[error("Failed to read redirect URI from stdin")]
|
||||
AuthCodeStdinRead,
|
||||
|
||||
/// Could not bind TCP listener to the specified socket address for OAuth callback.
|
||||
#[error("Failed to bind server to {addr} ({e})")]
|
||||
AuthCodeListenerBind { addr: SocketAddr, e: io::Error },
|
||||
AuthCodeListenerBind {
|
||||
/// Callback address.
|
||||
addr: SocketAddr,
|
||||
/// Inner error code.
|
||||
e: io::Error,
|
||||
},
|
||||
|
||||
/// Listener terminated before receiving an OAuth callback connection.
|
||||
#[error("Listener terminated without accepting a connection")]
|
||||
AuthCodeListenerTerminated,
|
||||
|
||||
/// Failed to read incoming HTTP request containing OAuth callback.
|
||||
#[error("Failed to read redirect URI from HTTP request")]
|
||||
AuthCodeListenerRead,
|
||||
|
||||
/// Received malformed HTTP request for OAuth callback.
|
||||
#[error("Failed to parse redirect URI from HTTP request")]
|
||||
AuthCodeListenerParse,
|
||||
|
||||
/// Could not send HTTP response after handling OAuth callback.
|
||||
#[error("Failed to write HTTP response")]
|
||||
AuthCodeListenerWrite,
|
||||
|
||||
/// Invalid Spotify authorization endpoint URL.
|
||||
#[error("Invalid Spotify OAuth URI")]
|
||||
InvalidSpotifyUri,
|
||||
|
||||
/// Redirect URI failed validation.
|
||||
#[error("Invalid Redirect URI {uri} ({e})")]
|
||||
InvalidRedirectUri { uri: String, e: url::ParseError },
|
||||
InvalidRedirectUri {
|
||||
/// Auth URI.
|
||||
uri: String,
|
||||
/// Inner error code
|
||||
e: url::ParseError,
|
||||
},
|
||||
|
||||
/// Channel communication failure.
|
||||
#[error("Failed to receive code")]
|
||||
Recv,
|
||||
|
||||
/// Token exchange failure with Spotify's authorization server.
|
||||
#[error("Failed to exchange code for access token ({e})")]
|
||||
ExchangeCode { e: String },
|
||||
ExchangeCode {
|
||||
/// Inner error description
|
||||
e: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Represents an OAuth token used for accessing Spotify's Web API and sessions.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OAuthToken {
|
||||
/// Bearer token used for authenticated Spotify API requests
|
||||
pub access_token: String,
|
||||
/// Long-lived token used to obtain new access tokens
|
||||
pub refresh_token: String,
|
||||
/// Instant when the access token becomes invalid
|
||||
pub expires_at: Instant,
|
||||
/// Type of token
|
||||
pub token_type: String,
|
||||
/// Permission scopes granted by this token
|
||||
pub scopes: Vec<String>,
|
||||
}
|
||||
|
||||
|
@ -104,7 +147,10 @@ fn get_authcode_stdin() -> Result<AuthorizationCode, OAuthError> {
|
|||
}
|
||||
|
||||
/// Spawn HTTP server at provided socket address to accept OAuth callback and return auth code.
|
||||
fn get_authcode_listener(socket_address: SocketAddr) -> Result<AuthorizationCode, OAuthError> {
|
||||
fn get_authcode_listener(
|
||||
socket_address: SocketAddr,
|
||||
message: String,
|
||||
) -> Result<AuthorizationCode, OAuthError> {
|
||||
let listener =
|
||||
TcpListener::bind(socket_address).map_err(|e| OAuthError::AuthCodeListenerBind {
|
||||
addr: socket_address,
|
||||
|
@ -130,7 +176,6 @@ fn get_authcode_listener(socket_address: SocketAddr) -> Result<AuthorizationCode
|
|||
.ok_or(OAuthError::AuthCodeListenerParse)?;
|
||||
let code = get_code(&("http://localhost".to_string() + redirect_url));
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
|
@ -146,6 +191,7 @@ fn get_authcode_listener(socket_address: SocketAddr) -> Result<AuthorizationCode
|
|||
// If the specified `redirect_uri` is HTTP, loopback, and contains a port,
|
||||
// then the corresponding socket address is returned.
|
||||
fn get_socket_address(redirect_uri: &str) -> Option<SocketAddr> {
|
||||
#![warn(missing_docs)]
|
||||
let url = match Url::parse(redirect_uri) {
|
||||
Ok(u) if u.scheme() == "http" && u.port().is_some() => u,
|
||||
_ => return None,
|
||||
|
@ -162,6 +208,215 @@ fn get_socket_address(redirect_uri: &str) -> Option<SocketAddr> {
|
|||
None
|
||||
}
|
||||
|
||||
/// Struct that handle obtaining and refreshing access tokens.
|
||||
pub struct OAuthClient {
|
||||
scopes: Vec<String>,
|
||||
redirect_uri: String,
|
||||
should_open_url: bool,
|
||||
message: String,
|
||||
client: BasicClient,
|
||||
}
|
||||
|
||||
impl OAuthClient {
|
||||
/// Generates and opens/shows the authorization URL to obtain an access token.
|
||||
///
|
||||
/// Returns a verifier that must be included in the final request for validation.
|
||||
fn set_auth_url(&self) -> PkceCodeVerifier {
|
||||
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
// Generate the full authorization URL.
|
||||
// Some of these scopes are unavailable for custom client IDs. Which?
|
||||
let request_scopes: Vec<oauth2::Scope> =
|
||||
self.scopes.iter().map(|s| Scope::new(s.into())).collect();
|
||||
let (auth_url, _) = self
|
||||
.client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
.add_scopes(request_scopes)
|
||||
.set_pkce_challenge(pkce_challenge)
|
||||
.url();
|
||||
|
||||
if self.should_open_url {
|
||||
open::that_in_background(auth_url.as_str());
|
||||
}
|
||||
println!("Browse to: {}", auth_url);
|
||||
|
||||
pkce_verifier
|
||||
}
|
||||
|
||||
fn build_token(
|
||||
&self,
|
||||
resp: StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>,
|
||||
) -> Result<OAuthToken, OAuthError> {
|
||||
trace!("Obtained new access token: {resp:?}");
|
||||
|
||||
let token_scopes: Vec<String> = match resp.scopes() {
|
||||
Some(s) => s.iter().map(|s| s.to_string()).collect(),
|
||||
_ => self.scopes.clone(),
|
||||
};
|
||||
let refresh_token = match resp.refresh_token() {
|
||||
Some(t) => t.secret().to_string(),
|
||||
_ => "".to_string(), // Spotify always provides a refresh token.
|
||||
};
|
||||
Ok(OAuthToken {
|
||||
access_token: resp.access_token().secret().to_string(),
|
||||
refresh_token,
|
||||
expires_at: Instant::now()
|
||||
+ resp
|
||||
.expires_in()
|
||||
.unwrap_or_else(|| Duration::from_secs(3600)),
|
||||
token_type: format!("{:?}", resp.token_type()),
|
||||
scopes: token_scopes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Syncronously obtain a Spotify access token using the authorization code with PKCE OAuth flow.
|
||||
pub fn get_access_token(&self) -> Result<OAuthToken, OAuthError> {
|
||||
let pkce_verifier = self.set_auth_url();
|
||||
|
||||
let code = match get_socket_address(&self.redirect_uri) {
|
||||
Some(addr) => get_authcode_listener(addr, self.message.clone()),
|
||||
_ => get_authcode_stdin(),
|
||||
}?;
|
||||
trace!("Exchange {code:?} for access token");
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let client = self.client.clone();
|
||||
std::thread::spawn(move || {
|
||||
let resp = client
|
||||
.exchange_code(code)
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request(http_client);
|
||||
if let Err(e) = tx.send(resp) {
|
||||
error!("OAuth channel send error: {e}");
|
||||
}
|
||||
});
|
||||
let channel_response = rx.recv().map_err(|_| OAuthError::Recv)?;
|
||||
let token_response =
|
||||
channel_response.map_err(|e| OAuthError::ExchangeCode { e: e.to_string() })?;
|
||||
|
||||
self.build_token(token_response)
|
||||
}
|
||||
|
||||
/// Synchronously obtain a new valid OAuth token from `refresh_token`
|
||||
pub fn refresh_token(&self, refresh_token: &str) -> Result<OAuthToken, OAuthError> {
|
||||
let refresh_token = RefreshToken::new(refresh_token.to_string());
|
||||
let resp = self
|
||||
.client
|
||||
.exchange_refresh_token(&refresh_token)
|
||||
.request(http_client);
|
||||
|
||||
let resp = resp.map_err(|e| OAuthError::ExchangeCode { e: e.to_string() })?;
|
||||
self.build_token(resp)
|
||||
}
|
||||
|
||||
/// Asyncronously obtain a Spotify access token using the authorization code with PKCE OAuth flow.
|
||||
pub async fn get_access_token_async(&self) -> Result<OAuthToken, OAuthError> {
|
||||
let pkce_verifier = self.set_auth_url();
|
||||
|
||||
let code = match get_socket_address(&self.redirect_uri) {
|
||||
Some(addr) => get_authcode_listener(addr, self.message.clone()),
|
||||
_ => get_authcode_stdin(),
|
||||
}?;
|
||||
trace!("Exchange {code:?} for access token");
|
||||
|
||||
let resp = self
|
||||
.client
|
||||
.exchange_code(code)
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(async_http_client)
|
||||
.await;
|
||||
|
||||
let resp = resp.map_err(|e| OAuthError::ExchangeCode { e: e.to_string() })?;
|
||||
self.build_token(resp)
|
||||
}
|
||||
|
||||
/// Asynchronously obtain a new valid OAuth token from `refresh_token`
|
||||
pub async fn refresh_token_async(&self, refresh_token: &str) -> Result<OAuthToken, OAuthError> {
|
||||
let refresh_token = RefreshToken::new(refresh_token.to_string());
|
||||
let resp = self
|
||||
.client
|
||||
.exchange_refresh_token(&refresh_token)
|
||||
.request_async(async_http_client)
|
||||
.await;
|
||||
|
||||
let resp = resp.map_err(|e| OAuthError::ExchangeCode { e: e.to_string() })?;
|
||||
self.build_token(resp)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder struct through which structures of type OAuthClient are instantiated.
|
||||
pub struct OAuthClientBuilder {
|
||||
client_id: String,
|
||||
redirect_uri: String,
|
||||
scopes: Vec<String>,
|
||||
should_open_url: bool,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl OAuthClientBuilder {
|
||||
/// Create a new OAuthClientBuilder with provided params and default config.
|
||||
///
|
||||
/// `redirect_uri` must match to the registered Uris of `client_id`
|
||||
pub fn new(client_id: &str, redirect_uri: &str, scopes: Vec<&str>) -> Self {
|
||||
Self {
|
||||
client_id: client_id.to_string(),
|
||||
redirect_uri: redirect_uri.to_string(),
|
||||
scopes: scopes.into_iter().map(Into::into).collect(),
|
||||
should_open_url: false,
|
||||
message: String::from("Go back to your terminal :)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// When this function is added to the building process pipeline, the auth url will be
|
||||
/// opened with the default web browser. Otherwise, it will be printed to standard output.
|
||||
pub fn open_in_browser(mut self) -> Self {
|
||||
self.should_open_url = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// When this function is added to the building process pipeline, the body of the response to
|
||||
/// the callback request will be `message`. This is useful to load custom HTMLs to that &str.
|
||||
pub fn with_custom_message(mut self, message: &str) -> Self {
|
||||
self.message = message.to_string();
|
||||
self
|
||||
}
|
||||
|
||||
/// End of the building process pipeline. If Ok, a OAuthClient instance will be returned.
|
||||
pub fn build(self) -> Result<OAuthClient, OAuthError> {
|
||||
let auth_url = AuthUrl::new("https://accounts.spotify.com/authorize".to_string())
|
||||
.map_err(|_| OAuthError::InvalidSpotifyUri)?;
|
||||
let token_url = TokenUrl::new("https://accounts.spotify.com/api/token".to_string())
|
||||
.map_err(|_| OAuthError::InvalidSpotifyUri)?;
|
||||
let redirect_url = RedirectUrl::new(self.redirect_uri.clone()).map_err(|e| {
|
||||
OAuthError::InvalidRedirectUri {
|
||||
uri: self.redirect_uri.clone(),
|
||||
e,
|
||||
}
|
||||
})?;
|
||||
|
||||
let client = BasicClient::new(
|
||||
ClientId::new(self.client_id.to_string()),
|
||||
None,
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
.set_redirect_uri(redirect_url);
|
||||
|
||||
Ok(OAuthClient {
|
||||
scopes: self.scopes,
|
||||
should_open_url: self.should_open_url,
|
||||
message: self.message,
|
||||
redirect_uri: self.redirect_uri,
|
||||
client,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain a Spotify access token using the authorization code with PKCE OAuth flow.
|
||||
/// The `redirect_uri` must match what is registered to the client ID.
|
||||
#[deprecated(
|
||||
since = "0.7.0",
|
||||
note = "please use builder pattern with `OAuthClientBuilder` instead"
|
||||
)]
|
||||
/// Obtain a Spotify access token using the authorization code with PKCE OAuth flow.
|
||||
/// The redirect_uri must match what is registered to the client ID.
|
||||
pub fn get_access_token(
|
||||
|
@ -204,7 +459,7 @@ pub fn get_access_token(
|
|||
println!("Browse to: {}", auth_url);
|
||||
|
||||
let code = match get_socket_address(redirect_uri) {
|
||||
Some(addr) => get_authcode_listener(addr),
|
||||
Some(addr) => get_authcode_listener(addr, String::from("Go back to your terminal :)")),
|
||||
_ => get_authcode_stdin(),
|
||||
}?;
|
||||
trace!("Exchange {code:?} for access token");
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue