librespot/examples/get_token.rs
Nick Steel 4f9151c642
Credentials with access token (oauth) (#1309)
* core: Create credentials from access token via OAuth2

* core: Credentials.username is optional: not required for token auth.

* core: store auth data within session. We might need this later if need to re-auth and original creds are no longer valid/available.

* bin: New --token arg for using Spotify access token. Specify 0 to manually enter the auth code (headless).

* bin: Added --enable-oauth / -j option. Using --password / -p option will error and exit.

* core: reconnect session if using token authentication

Token authenticated sessions cannot use keymaster. So reconnect using the reusable credentials we just obtained. Can perhaps remove this
workaround once keymaster is replaced with login5.

* examples: replace password login with token login
2024-09-13 07:35:55 +02:00

40 lines
1.3 KiB
Rust

use std::env;
use librespot::core::{authentication::Credentials, config::SessionConfig, session::Session};
const SCOPES: &str =
"streaming,user-read-playback-state,user-modify-playback-state,user-read-currently-playing";
#[tokio::main]
async fn main() {
let mut builder = env_logger::Builder::new();
builder.parse_filters("librespot=trace");
builder.init();
let mut session_config = SessionConfig::default();
let args: Vec<_> = env::args().collect();
if args.len() == 3 {
// Only special client IDs have sufficient privileges e.g. Spotify's.
session_config.client_id = args[2].clone()
} else if args.len() != 2 {
eprintln!("Usage: {} ACCESS_TOKEN [CLIENT_ID]", args[0]);
return;
}
let access_token = &args[1];
// Now create a new session with that token.
let session = Session::new(session_config.clone(), None);
let credentials = Credentials::with_access_token(access_token);
println!("Connecting with token..");
match session.connect(credentials, false).await {
Ok(()) => println!("Session username: {:#?}", session.username()),
Err(e) => {
println!("Error connecting: {e}");
return;
}
};
let token = session.token_provider().get_token(SCOPES).await.unwrap();
println!("Got me a token: {token:#?}");
}