### Authenticate with Minecraft using Microsoft OAuth2 - Rust Source: https://github.com/minecraft-rs/minecraft-msa-auth/blob/main/README.md This Rust code snippet demonstrates how to authenticate into Minecraft online services using a Microsoft OAuth2 token. It uses the `minecraft-msa-auth` crate along with `oauth2-rs` to handle the authentication flow, including device code retrieval, token exchange, and Minecraft token retrieval. Dependencies include the `minecraft-msa-auth` and `oauth2-rs` crates. ```rust const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"; const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"; const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; let client = BasicClient::new( ClientId::new(client_id), None, AuthUrl::new(MSA_AUTHORIZE_URL.to_string())?, Some(TokenUrl::new(MSA_TOKEN_URL.to_string())?), ) .set_device_authorization_url(DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_string())?); let details: StandardDeviceAuthorizationResponse = client .exchange_device_code()? .add_scope(Scope::new("XboxLive.signin offline_access".to_string())) .request_async(async_http_client) .await?; println!( "Open this URL in your browser: {} and enter the code: {}", details.verification_uri().to_string(), details.user_code().secret().to_string() ); let token = client .exchange_device_access_token(&details) .request_async(async_http_client, tokio::time::sleep, None) .await?; println!("microsoft token: {:?}", token); let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); let mc_token = mc_flow.exchange_microsoft_token(token.access_token()).await?; println!("minecraft token: {:?}", mc_token); ``` -------------------------------- ### Rust Minecraft MSA Authorization Code Flow with PKCE Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt Performs a full OAuth2 Authorization Code Flow with PKCE for Microsoft accounts. It configures the OAuth client, generates PKCE parameters, constructs the authorization URL, listens for the callback, exchanges the code for tokens, and finally exchanges the Microsoft token for a Minecraft token. Dependencies include `minecraft-msa-auth`, `oauth2`, `reqwest`, and `tokio`. ```rust use minecraft_msa_auth::MinecraftAuthorizationFlow; use oauth2::basic::BasicClient; use oauth2::reqwest::async_http_client; use oauth2::{ AuthType, AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse, TokenUrl, }; use reqwest::{Client, Url}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::TcpListener; #[tokio::main] async fn main() -> Result<(), Box> { let client_id = "your-client-id-here"; // Configure OAuth2 client with local redirect let client = BasicClient::new( ClientId::new(client_id.to_string()), None, AuthUrl::new("https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize".to_string())?, Some(TokenUrl::new( "https://login.microsoftonline.com/consumers/oauth2/v2.0/token".to_string(), )?), ) .set_auth_type(AuthType::RequestBody) .set_redirect_uri( RedirectUrl::new("http://127.0.0.1:8114/redirect".to_string())?, ); // Generate PKCE challenge for enhanced security let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256(); // Generate authorization URL let (authorize_url, csrf_state) = client .authorize_url(CsrfToken::new_random) .add_scope(Scope::new("XboxLive.signin offline_access".to_string())) .set_pkce_challenge(pkce_code_challenge) .url(); println!("Open this URL in your browser:\n{}\n", authorize_url); // Start local server to receive OAuth callback let listener = TcpListener::bind("127.0.0.1:8114").await?; let (stream, _) = listener.accept().await?; stream.readable().await?; let mut stream = BufReader::new(stream); // Parse authorization code from redirect let mut request_line = String::new(); stream.read_line(&mut request_line).await?; let redirect_url = request_line.split_whitespace().nth(1).unwrap(); let url = Url::parse(&("http://localhost".to_string() + redirect_url))?; let (_key, code_value) = url.query_pairs().find(|(key, _)| key == "code").unwrap(); let code = AuthorizationCode::new(code_value.into_owned()); let (_key, state_value) = url.query_pairs().find(|(key, _)| key == "state").unwrap(); let state = CsrfToken::new(state_value.into_owned()); // Send response to browser let message = "Authentication successful! Return to your application."; let response = format!( "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{ " message.len(), message ); stream.write_all(response.as_bytes()).await?; // Verify CSRF state assert_eq!(state.secret(), csrf_state.secret()); // Exchange authorization code for token let token = client .exchange_code(code) .set_pkce_verifier(pkce_code_verifier) .request_async(async_http_client) .await?; println!("Microsoft token acquired: {:?}", token.access_token()); // Exchange Microsoft token for Minecraft token let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); let mc_token = mc_flow.exchange_microsoft_token(token.access_token().secret()).await?; println!("Minecraft authentication complete!"); println!("Token: {:?}", mc_token); Ok(()) } ``` -------------------------------- ### Initialize MinecraftAuthorizationFlow with HTTP Client (Rust) Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt Creates a new instance of MinecraftAuthorizationFlow, which is essential for initiating the authentication process. It requires an HTTP client, such as one from the `reqwest` crate, to perform network requests during the authentication flow. ```rust use minecraft_msa_auth::MinecraftAuthorizationFlow; use reqwest::Client; #[tokio::main] async fn main() { // Initialize the authorization flow with a reqwest HTTP client let http_client = Client::new(); let mc_flow = MinecraftAuthorizationFlow::new(http_client); // The flow instance is now ready to exchange Microsoft tokens // for Minecraft authentication tokens } ``` -------------------------------- ### Rust: MSA Device Code Flow Authentication Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt This Rust code demonstrates the OAuth2 device code grant flow for Microsoft MSA authentication. It requests device authorization, prompts the user to verify on a device, polls for the access token, and then exchanges it for a Minecraft token. Dependencies include the `minecraft-msa-auth`, `oauth2`, and `reqwest` crates. It takes no explicit input but requires user interaction via a browser and input code. ```rust use minecraft_msa_auth::MinecraftAuthorizationFlow; use oauth2::basic::BasicClient; use oauth2::devicecode::StandardDeviceAuthorizationResponse; use oauth2::reqwest::async_http_client; use oauth2::{AuthUrl, ClientId, DeviceAuthorizationUrl, Scope, TokenResponse, TokenUrl}; use reqwest::Client; const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"; const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"; const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; #[tokio::main] async fn main() -> Result<(), Box> { // Your Azure AD application client ID let client_id = "your-client-id-here"; // Configure OAuth2 client for Microsoft device flow let client = BasicClient::new( ClientId::new(client_id.to_string()), None, AuthUrl::new(MSA_AUTHORIZE_URL.to_string())?, Some(TokenUrl::new(MSA_TOKEN_URL.to_string())?), ) .set_device_authorization_url(DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_string())?); // Request device authorization with Xbox Live scope let details: StandardDeviceAuthorizationResponse = client .exchange_device_code()? .add_scope(Scope::new("XboxLive.signin offline_access".to_string())) .request_async(async_http_client) .await?; // Display instructions to user println!( "Open this URL in your browser:\n{}\nand enter the code: {}", details.verification_uri().to_string(), details.user_code().secret().to_string() ); // Poll for token (blocks until user completes authentication) let token = client .exchange_device_access_token(&details) .request_async(async_http_client, tokio::time::sleep, None) .await?; println!("Microsoft token acquired: {:?}", token.access_token()); // Exchange Microsoft token for Minecraft token let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); let mc_token = mc_flow.exchange_microsoft_token(token.access_token().secret()).await?; println!("Successfully authenticated!"); println!("Minecraft token: {:?}", mc_token); println!("Xbox username: {}", mc_token.username()); Ok(()) } ``` -------------------------------- ### Handle Minecraft Authentication Errors in Rust Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt Demonstrates comprehensive error handling for various Minecraft authentication failures using the `minecraft-msa-auth` crate. It covers specific errors like `AddToFamily`, `NoXbox`, `MissingClaims`, and network issues related to `reqwest`. ```rust use minecraft_msa_auth::{MinecraftAuthorizationFlow, MinecraftAuthorizationError}; use reqwest::Client; #[tokio::main] async fn main() { let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); let microsoft_token = "user-microsoft-token"; match mc_flow.exchange_microsoft_token(microsoft_token).await { Ok(mc_token) => { println!("Authentication successful!"); println!("Username: {}", mc_token.username()); println!("Expires in: {} seconds", mc_token.expires_in()); } Err(MinecraftAuthorizationError::AddToFamily) => { eprintln!("Error: Minor account must be added to Microsoft Family"); eprintln!("Please add this account to a Microsoft Family to continue"); } Err(MinecraftAuthorizationError::NoXbox) => { eprintln!("Error: Xbox account required"); eprintln!("Please create an Xbox account at xbox.com to use Minecraft"); } Err(MinecraftAuthorizationError::MissingClaims) => { eprintln!("Error: Authentication response missing required claims"); eprintln!("This may indicate an issue with the Microsoft token"); } Err(MinecraftAuthorizationError::Reqwest(e)) => { eprintln!("Network error during authentication: {}", e); eprintln!("Please check your internet connection and try again"); } } } ``` -------------------------------- ### Access Minecraft Authentication Response Fields in Rust Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt Shows how to extract key information such as the access token, username, token type, and expiration time from a successful Minecraft authentication response. It also demonstrates using the access token to fetch the user's Minecraft profile. ```rust use minecraft_msa_auth::{MinecraftAuthorizationFlow, MinecraftAuthenticationResponse}; use reqwest::Client; async fn authenticate_and_use_token(microsoft_token: &str) -> Result<(), Box> { let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); let response: MinecraftAuthenticationResponse = mc_flow .exchange_microsoft_token(microsoft_token) .await?; // Get the Minecraft access token (implements Debug with redaction) let access_token = response.access_token(); // Get the Xbox username (NOT the Minecraft player UUID) let xbox_username = response.username(); // Get the token type (typically Bearer) let token_type = response.token_type(); // Get token expiration time in seconds let expires_in = response.expires_in(); // Use the token in Minecraft API requests let client = Client::new(); let profile_response = client .get("https://api.minecraftservices.com/minecraft/profile") .bearer_auth(access_token.as_ref()) .send() .await?; println!("Token valid for {} seconds", expires_in); println!("Profile response: {:?}", profile_response.text().await?); Ok(()) } ``` -------------------------------- ### Exchange Microsoft Token for Minecraft Access Token (Rust) Source: https://context7.com/minecraft-rs/minecraft-msa-auth/llms.txt Exchanges a valid Microsoft OAuth2 access token for Minecraft service credentials. This process involves interacting with Xbox Live authentication. The function returns a structure containing the Minecraft access token, username, token type, and expiration time. ```rust use minecraft_msa_auth::{MinecraftAuthorizationFlow, MinecraftAuthorizationError}; use reqwest::Client; #[tokio::main] async fn main() -> Result<(), MinecraftAuthorizationError> { // Assume we have a valid Microsoft access token let microsoft_token = "EwAoA8l6BAAURSN/FHl..."; // Microsoft OAuth2 access token // Create the authorization flow let mc_flow = MinecraftAuthorizationFlow::new(Client::new()); // Exchange the Microsoft token for Minecraft credentials let mc_token = mc_flow.exchange_microsoft_token(microsoft_token).await?; // Access the authentication response fields println!("Minecraft Access Token: {:?}", mc_token.access_token()); println!("Xbox Username: {}", mc_token.username()); println!("Token Type: {:?}", mc_token.token_type()); println!("Expires in: {} seconds", mc_token.expires_in()); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.