### Full Device Code Login and Persistence Example Source: https://github.com/raphimc/minecraftauth/blob/main/README.md A complete implementation showing the login process, initial token saving to a file, and setting up an automatic file-writing listener for subsequent token refreshes. ```java File tokenFile = new File("tokens.json"); JavaAuthManager authManager = JavaAuthManager.create(MinecraftAuth.createHttpClient()).login(DeviceCodeMsaAuthService::new, deviceCode -> System.out.println("Go to " + deviceCode.getDirectVerificationUri())); Files.write(tokenFile.toPath(), JavaAuthManager.toJson(authManager).toString().getBytes(StandardCharsets.UTF_8)); authManager.getChangeListeners().add(() -> { try { Files.write(tokenFile.toPath(), JavaAuthManager.toJson(authManager).toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } }); System.out.println("Access token: " + authManager.getMinecraftToken().getUpToDate().getToken()); ``` -------------------------------- ### Implement Complete Minecraft Authentication Flow in Java Source: https://context7.com/raphimc/minecraftauth/llms.txt This example demonstrates the full authentication lifecycle, including loading saved sessions, performing a new device-code login, and setting up automatic token persistence. It also shows how to access Minecraft profile data and interact with the Realms service. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import net.raphimc.minecraftauth.extra.realms.service.impl.JavaRealmsService; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.File; import java.nio.file.Files; import java.nio.charset.StandardCharsets; public class MinecraftAuthExample { private static final File TOKEN_FILE = new File("minecraft_tokens.json"); public static void main(String[] args) throws Exception { HttpClient httpClient = MinecraftAuth.createHttpClient("MyMinecraftApp/1.0"); JavaAuthManager authManager; if (TOKEN_FILE.exists()) { String json = new String(Files.readAllBytes(TOKEN_FILE.toPath()), StandardCharsets.UTF_8); JsonObject savedData = JsonParser.parseString(json).getAsJsonObject(); authManager = JavaAuthManager.fromJson(httpClient, savedData); authManager.getMinecraftToken().refreshIfExpired(); } else { authManager = JavaAuthManager.create(httpClient) .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Please visit: " + deviceCode.getDirectVerificationUri()); }); authManager.getMinecraftToken().refresh(); authManager.getMinecraftProfile().refresh(); } authManager.getChangeListeners().add(() -> { try { JsonObject json = JavaAuthManager.toJson(authManager); Files.write(TOKEN_FILE.toPath(), json.toString().getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { System.err.println("Failed to save tokens: " + e.getMessage()); } }); var profile = authManager.getMinecraftProfile().getUpToDate(); System.out.println("Logged in as: " + profile.getName()); JavaRealmsService realmsService = new JavaRealmsService(httpClient, "1.20.4", authManager.getMinecraftToken(), authManager.getMinecraftProfile()); if (realmsService.isCompatible()) { var realms = realmsService.getWorlds(); System.out.println("Available Realms: " + realms.size()); } } } ``` -------------------------------- ### Create HttpClient for MinecraftAuth Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Demonstrates how to create an HttpClient instance for use with MinecraftAuth. It's recommended to use a custom user agent for network requests. This is a foundational step for all authentication processes. ```java HttpClient httpClient = MinecraftAuth.createHttpClient(userAgent); // Or you can create an HttpClient without a custom user agent (not recommended) HttpClient httpClient = MinecraftAuth.createHttpClient(); ``` -------------------------------- ### Configure HTTP Client for MinecraftAuth Source: https://context7.com/raphimc/minecraftauth/llms.txt Initializes a pre-configured HttpClient with necessary timeouts and headers. Providing a custom user agent is recommended to prevent rate limiting during authentication requests. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.lenni0451.commons.httpclient.HttpClient; // Create an HttpClient with a custom user agent (recommended) HttpClient httpClient = MinecraftAuth.createHttpClient("MyApplication/1.0"); // Or create an HttpClient with default user agent (not recommended for production) HttpClient httpClient = MinecraftAuth.createHttpClient(); ``` -------------------------------- ### Java Edition Authentication with Local Web Server Source: https://context7.com/raphimc/minecraftauth/llms.txt Demonstrates how to authenticate for Minecraft: Java Edition using a local web server to handle the OAuth callback. This method requires a custom MSA application configuration with a specific redirect URI. ```APIDOC ## Java Edition Authentication with Local Web Server ### Description Authenticates for Minecraft: Java Edition by starting a local HTTP server to receive the OAuth callback. This requires configuring a custom MSA application with a redirect URI. ### Method N/A (Code Example) ### Endpoint N/A (Local Web Server) ### Parameters N/A ### Request Example ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.LocalWebServerMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaApplicationConfig; import net.lenni0451.commons.httpclient.HttpClient; import java.awt.Desktop; import java.net.URL; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Custom application config with redirect URI MsaApplicationConfig appConfig = new MsaApplicationConfig( "your-client-id", "XboxLive.signin offline_access", null, // client secret (optional) "http://localhost/callback", // redirect URI MsaEnvironment.LIVE ); JavaAuthManager authManager = JavaAuthManager.create(httpClient) .msaApplicationConfig(appConfig) .login(LocalWebServerMsaAuthService::new, url -> { // Open the URL in the user's default browser try { Desktop.getDesktop().browse(url.toURI()); } catch (Exception e) { System.out.println("Open this URL: " + url); } }); System.out.println("Logged in as: " + authManager.getMinecraftProfile().getUpToDate().getName()); ``` ### Response N/A (Code Example) ### Response Example N/A (Code Example) ``` -------------------------------- ### Configure Custom MSA Application Source: https://context7.com/raphimc/minecraftauth/llms.txt Shows how to initialize a custom MsaApplicationConfig for Microsoft authentication. This allows developers to specify their own Azure client IDs, scopes, and redirect URIs when using the JavaAuthManager. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.model.MsaApplicationConfig; import net.raphimc.minecraftauth.msa.data.MsaConstants; import net.raphimc.minecraftauth.msa.data.MsaEnvironment; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); MsaApplicationConfig customConfig = new MsaApplicationConfig( "your-azure-client-id", "XboxLive.signin offline_access", "your-client-secret", "http://localhost:8080/callback", MsaEnvironment.MICROSOFT_ONLINE_CONSUMERS ); JavaAuthManager authManager = JavaAuthManager.create(httpClient) .msaApplicationConfig(customConfig) .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Go to: " + deviceCode.getDirectVerificationUri()); }); ``` -------------------------------- ### Configure Custom MSA Authentication Service Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Demonstrates how to instantiate a DeviceCodeMsaAuthService with custom configuration and timeout settings. This is useful for implementing specific login flows or modifying default behavior. ```java DeviceCodeMsaAuthService authService = new DeviceCodeMsaAuthService(MinecraftAuth.createHttpClient(), new MsaApplicationConfig(MsaConstants.JAVA_TITLE_ID, MsaConstants.SCOPE_TITLE_AUTH), new Consumer() { @Override public void accept(MsaDeviceCode deviceCode) { System.out.println("Go to " + deviceCode.getDirectVerificationUri()); } }, 60_000); MsaToken msaToken = authService.acquireToken(); JavaAuthManager authManager = JavaAuthManager.create(MinecraftAuth.createHttpClient()).login(msaToken); ``` -------------------------------- ### Manage Token Lifecycle with Holder Source: https://context7.com/raphimc/minecraftauth/llms.txt Demonstrates how to use the Holder class to manage Minecraft tokens and profiles. It covers methods for retrieving up-to-date tokens, accessing cached values, and manually triggering refreshes. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.java.model.MinecraftToken; import net.raphimc.minecraftauth.java.model.MinecraftProfile; import net.raphimc.minecraftauth.util.holder.Holder; JavaAuthManager authManager = /* ... authenticated manager ... */; Holder tokenHolder = authManager.getMinecraftToken(); MinecraftToken freshToken = tokenHolder.getUpToDate(); System.out.println("Token: " + freshToken.getToken()); MinecraftToken cachedToken = tokenHolder.getCached(); tokenHolder.refreshIfExpired(); tokenHolder.refresh(); boolean hasToken = tokenHolder.hasValue(); Holder profileHolder = authManager.getMinecraftProfile(); MinecraftProfile profile = profileHolder.getUpToDate(); System.out.println("UUID: " + profile.getId()); System.out.println("Name: " + profile.getName()); ``` -------------------------------- ### Saving and Loading Authentication State with JSON Source: https://context7.com/raphimc/minecraftauth/llms.txt Demonstrates how to save and load Minecraft authentication tokens using JSON serialization. It includes setting up change listeners to automatically save tokens upon refresh and restoring the authentication state from a file. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import com.google.gson.JsonObject; import java.io.File; import java.nio.file.Files; import java.nio.charset.StandardCharsets; File tokenFile = new File("tokens.json"); HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Login and save tokens JavaAuthManager authManager = JavaAuthManager.create(httpClient) .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Go to: " + deviceCode.getDirectVerificationUri()); }); // Request tokens that should be cached authManager.getMinecraftToken().refresh(); authManager.getMinecraftProfile().refresh(); // Save tokens to file JsonObject serializedAuthManager = JavaAuthManager.toJson(authManager); Files.write(tokenFile.toPath(), serializedAuthManager.toString().getBytes(StandardCharsets.UTF_8)); // Add change listener to auto-save on token refresh authManager.getChangeListeners().add(() -> { try { JsonObject json = JavaAuthManager.toJson(authManager); Files.write(tokenFile.toPath(), json.toString().getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { e.printStackTrace(); } }); // Later, restore from saved tokens String savedJson = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8); JsonObject json = new com.google.gson.JsonParser().parse(savedJson).getAsJsonObject(); JavaAuthManager restoredAuthManager = JavaAuthManager.fromJson(httpClient, json); // Refresh tokens if expired restoredAuthManager.getMinecraftToken().refreshIfExpired(); System.out.println("Restored user: " + restoredAuthManager.getMinecraftProfile().getUpToDate().getName()); ``` -------------------------------- ### Minecraft Realms API Implementation (Java Edition) Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Provides a basic implementation of the Minecraft Realms API for Java Edition. It allows listing and joining realms, requiring the latest supported client version and user authentication tokens. Handles TOS acceptance for joining worlds. ```java JavaRealmsService javaRealmsService = new JavaRealmsService(httpClient, "latestSupportedClientVersionHere", authManager.getMinecraftToken(), authManager.getMinecraftProfile()); boolean isCompatible = javaRealmsService.isCompatible(); if (!isCompatible) { System.out.println("The client version does not support Realms"); } else { System.out.println("Your client supports Realms"); List realmsWorlds = javaRealmsService.getWorlds(); System.out.println("Realms worlds: " + realmsWorlds); try { System.out.println("Connect to: " + javaRealmsService.joinWorld(realmsWorlds.get(0))); } catch (RealmsRequestException e) { if (e.getErrorCode() == RealmsRequestException.ERROR_TOS_NOT_ACCEPTED) { // The Java Edition Realms API requires users to accept the Minecraft Realms Terms of Service (https://aka.ms/MinecraftRealmsTerms) // You should display the terms to the user and ask them to accept them: javaRealmsService.acceptTos(); // If they accept, then you can try to join the world again } } } ``` -------------------------------- ### Configure JavaAuthManager Builder Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Shows how to configure the JavaAuthManager builder, which is essential for setting up the authentication manager. You can use predefined application details or customize them with your own client ID, scope, and client secret. ```java // Use predefined application configuration (Uses the official Minecraft application details) JavaAuthManager.Builder authManagerBuilder = JavaAuthManager.create(httpClient); // If you want to customize the application details (like client id, scope or client secret) you can do it like this: JavaAuthManager.Builder authManagerBuilder = JavaAuthManager.create(httpClient).msaApplicationConfig(new MsaApplicationConfig(...)); ``` -------------------------------- ### Token Lifecycle Management Source: https://context7.com/raphimc/minecraftauth/llms.txt Explains how to use the Holder class to manage, refresh, and access cached Minecraft authentication tokens and profiles. ```APIDOC ## Token Lifecycle Management (Holder Class) ### Description The Holder class provides automated management for Minecraft tokens and profiles, supporting lazy loading, automatic refreshing, and manual cache control. ### Methods - **getUpToDate()**: Returns the current value, refreshing it automatically if it is expired or not yet set. - **getCached()**: Returns the cached value immediately without triggering a network request. - **refreshIfExpired()**: Triggers a refresh only if the current token is expired. - **refresh()**: Forces an immediate refresh of the token. - **hasValue()**: Checks if a valid cached value is currently available. ### Usage Example ```java Holder tokenHolder = authManager.getMinecraftToken(); MinecraftToken freshToken = tokenHolder.getUpToDate(); ``` ``` -------------------------------- ### Custom MSA Application Configuration Source: https://context7.com/raphimc/minecraftauth/llms.txt Details how to configure Microsoft Authentication (MSA) using custom Azure AD application credentials. ```APIDOC ## Custom MSA Application Configuration ### Description Use the MsaApplicationConfig class to override default Minecraft authentication settings with custom Azure AD application details. ### Configuration Parameters - **clientId** (String) - Required - The Azure AD Application Client ID. - **scopes** (String) - Required - Space-separated OAuth scopes. - **clientSecret** (String) - Optional - The client secret for confidential clients. - **redirectUri** (String) - Optional - The redirect URI for OAuth flows. - **environment** (MsaEnvironment) - Required - The Microsoft OAuth environment to target. ### Request Example ```java MsaApplicationConfig customConfig = new MsaApplicationConfig( "your-azure-client-id", "XboxLive.signin offline_access", "your-client-secret", "http://localhost:8080/callback", MsaEnvironment.MICROSOFT_ONLINE_CONSUMERS ); ``` ``` -------------------------------- ### Migrate MinecraftAuth 4.x to 5.x Data (Java) Source: https://context7.com/raphimc/minecraftauth/llms.txt This code snippet demonstrates how to migrate authentication data from MinecraftAuth 4.x.x format to 5.x.x. It loads old token data, uses `MinecraftAuth4To5Migrator` to convert Java Edition tokens, and then loads them into a new `JavaAuthManager`. Finally, it shows how to save the migrated data in the new format. Dependencies include Gson for JSON parsing and standard Java NIO for file operations. ```java import net.raphimc.minecraftauth.util.MinecraftAuth4To5Migrator; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.bedrock.BedrockAuthManager; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.nio.file.Files; import java.io.File; // Load old 4.x.x save data File oldSaveFile = new File("old_tokens.json"); String oldJson = new String(Files.readAllBytes(oldSaveFile.toPath())); JsonObject oldSaveData = JsonParser.parseString(oldJson).getAsJsonObject(); // Migrate Java Edition tokens JsonObject migratedJavaSave = MinecraftAuth4To5Migrator.migrateJavaSave(oldSaveData); // Or with custom MSA config: // JsonObject migratedJavaSave = MinecraftAuth4To5Migrator.migrateJavaSave(oldSaveData, customMsaConfig); // Load the migrated data into a new auth manager HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); JavaAuthManager javaAuthManager = JavaAuthManager.fromJson(httpClient, migratedJavaSave); // Migrate Bedrock Edition tokens JsonObject migratedBedrockSave = MinecraftAuth4To5Migrator.migrateBedrockSave(oldSaveData); BedrockAuthManager bedrockAuthManager = BedrockAuthManager.fromJson(httpClient, "1.20.0", migratedBedrockSave); // Save the migrated data in the new format Files.write(new File("new_tokens.json").toPath(), JavaAuthManager.toJson(javaAuthManager).toString().getBytes()); ``` -------------------------------- ### POST /auth/device-code Source: https://context7.com/raphimc/minecraftauth/llms.txt Initiates the Microsoft device code authentication flow for Minecraft Java Edition, allowing users to authenticate via a browser. ```APIDOC ## POST /auth/device-code ### Description Initiates the device code flow for Microsoft authentication. This is the recommended method as it supports 2FA. ### Method POST ### Endpoint /auth/device-code ### Parameters #### Request Body - **client_id** (string) - Required - The application client ID registered in the Azure portal. - **scope** (string) - Required - The requested OAuth scopes (e.g., "XboxLive.signin offline_access"). ### Request Example { "client_id": "your-client-id", "scope": "XboxLive.signin offline_access" } ### Response #### Success Response (200) - **device_code** (string) - The code to be entered by the user. - **user_code** (string) - The short code for display. - **verification_uri** (string) - The URL where the user enters the code. #### Response Example { "device_code": "ABC-123", "user_code": "XYZ-789", "verification_uri": "https://microsoft.com/devicelogin" } ``` -------------------------------- ### Minecraft Realms API Implementation (Bedrock Edition) Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Provides a basic implementation of the Minecraft Realms API for Bedrock Edition. It allows listing and joining realms, requiring the latest supported client version and XSTS token. Checks client compatibility before proceeding. ```java BedrockRealmsService bedrockRealmsService = new BedrockRealmsService(httpClient, "latestSupportedClientVersionHere", authManager.getRealmsXstsToken()); boolean isCompatible = bedrockRealmsService.isCompatible(); if (!isCompatible) { System.out.println("The client version does not support Realms"); } else { System.out.println("Your client supports Realms"); List realmsWorlds = bedrockRealmsService.getWorlds(); System.out.println("Realms worlds: " + realmsWorlds); System.out.println("Connect to: " + bedrockRealmsService.joinWorld(realmsWorlds.get(0))); } ``` -------------------------------- ### Java Edition Authentication with Local Web Server Source: https://context7.com/raphimc/minecraftauth/llms.txt Authenticates the Java Edition of Minecraft using a local web server to handle the OAuth callback. This method requires a custom MSA application with a configured redirect URI. It opens the authentication URL in the user's default browser. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.LocalWebServerMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaApplicationConfig; import net.lenni0451.commons.httpclient.HttpClient; import java.awt.Desktop; import java.net.URL; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Custom application config with redirect URI MsaApplicationConfig appConfig = new MsaApplicationConfig( "your-client-id", "XboxLive.signin offline_access", null, // client secret (optional) "http://localhost/callback", // redirect URI MsaEnvironment.LIVE ); JavaAuthManager authManager = JavaAuthManager.create(httpClient) .msaApplicationConfig(appConfig) .login(LocalWebServerMsaAuthService::new, url -> { // Open the URL in the user's default browser try { Desktop.getDesktop().browse(url.toURI()); } catch (Exception e) { System.out.println("Open this URL: " + url); } }); System.out.println("Logged in as: " + authManager.getMinecraftProfile().getUpToDate().getName()); ``` -------------------------------- ### Custom MSA Authentication Flow Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Demonstrates how to implement a custom DeviceCodeMsaAuthService to handle Microsoft Account authentication, including custom timeouts and verification URI handling. ```APIDOC ## Custom MSA Authentication ### Description Initializes a custom MSA authentication service using the Device Code flow, allowing for customized login parameters and verification callbacks. ### Method POST (Internal Library Flow) ### Parameters - **httpClient** (HttpClient) - Required - The HTTP client instance. - **config** (MsaApplicationConfig) - Required - Configuration containing Title ID and Scope. - **callback** (Consumer) - Required - Callback to handle the verification URI. - **timeout** (long) - Optional - Login timeout in milliseconds. ### Request Example ```java DeviceCodeMsaAuthService authService = new DeviceCodeMsaAuthService(httpClient, config, deviceCode -> { ... }, 60000); MsaToken msaToken = authService.acquireToken(); ``` ``` -------------------------------- ### Minecraft Java Edition Login using JavaFX WebView Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Demonstrates how to log in to Minecraft Java Edition using a JavaFX WebView. This method requires JavaFX to be set up in your project and opens a graphical window for the user to complete the login process. ```java JavaAuthManager authManager = authManagerBuilder.login(JfxWebViewMsaAuthService::new); ``` -------------------------------- ### Saving and Loading Authentication State Source: https://context7.com/raphimc/minecraftauth/llms.txt Explains how to persist and restore authentication tokens using JSON serialization. The library supports saving tokens automatically when they are refreshed via change listeners. ```APIDOC ## Saving and Loading Authentication State ### Description Supports JSON serialization of the authentication state, allowing tokens to be persisted and restored across application sessions. Change listeners can automatically save when tokens are refreshed. ### Method N/A (Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import com.google.gson.JsonObject; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; File tokenFile = new File("tokens.json"); HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Login and save tokens JavaAuthManager authManager = JavaAuthManager.create(httpClient) .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Go to: " + deviceCode.getDirectVerificationUri()); }); // Request tokens that should be cached authManager.getMinecraftToken().refresh(); authManager.getMinecraftProfile().refresh(); // Save tokens to file JsonObject serializedAuthManager = JavaAuthManager.toJson(authManager); Files.write(tokenFile.toPath(), serializedAuthManager.toString().getBytes(StandardCharsets.UTF_8)); // Add change listener to auto-save on token refresh authManager.getChangeListeners().add(() -> { try { JsonObject json = JavaAuthManager.toJson(authManager); Files.write(tokenFile.toPath(), json.toString().getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { e.printStackTrace(); } }); // Later, restore from saved tokens String savedJson = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8); JsonObject json = new com.google.gson.JsonParser().parse(savedJson).getAsJsonObject(); JavaAuthManager restoredAuthManager = JavaAuthManager.fromJson(httpClient, json); // Refresh tokens if expired restoredAuthManager.getMinecraftToken().refreshIfExpired(); System.out.println("Restored user: " + restoredAuthManager.getMinecraftProfile().getUpToDate().getName()); ``` ### Response N/A (Code Example) ### Response Example N/A (Code Example) ``` -------------------------------- ### Minecraft Java Edition Login using Credentials Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Provides a method for logging into Minecraft Java Edition using email and password credentials. Note that this method does not support 2FA and will fail if 2FA is enabled on the account. The device code flow is recommended for broader compatibility. ```java JavaAuthManager authManager = authManagerBuilder.login(CredentialsMsaAuthService::new, new MsaCredentials("email@test.com", "P4ssw0rd")); System.out.println("Username: " + authManager.getMinecraftProfile().getUpToDate().getName()); System.out.println("Access token: " + authManager.getMinecraftToken().getUpToDate().getToken()); ``` -------------------------------- ### POST /auth/credentials Source: https://context7.com/raphimc/minecraftauth/llms.txt Authenticates a user directly using email and password credentials. Note: Does not support accounts with 2FA enabled. ```APIDOC ## POST /auth/credentials ### Description Authenticates a user using their Microsoft account credentials. This method is not recommended for accounts with 2FA enabled. ### Method POST ### Endpoint /auth/credentials ### Parameters #### Request Body - **email** (string) - Required - The user's Microsoft account email. - **password** (string) - Required - The user's Microsoft account password. ### Request Example { "email": "user@example.com", "password": "securepassword123" } ### Response #### Success Response (200) - **access_token** (string) - The authenticated Microsoft access token. - **refresh_token** (string) - The token used to refresh the session. #### Response Example { "access_token": "eyJhbGci...", "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4=" } ``` -------------------------------- ### Token Serialization and Persistence Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Explains how to serialize the JavaAuthManager state to JSON for saving sessions and how to reload them later. ```APIDOC ## Token Serialization ### Description Converts the current authentication manager state into a JSON object for persistent storage. It is recommended to use change listeners to ensure the saved state remains updated as tokens are refreshed lazily. ### Methods - **JavaAuthManager.toJson(authManager)**: Serializes the manager to a JsonObject. - **JavaAuthManager.fromJson(httpClient, json)**: Restores the manager from a previously saved JsonObject. ### Implementation Example ```java // Save state JsonObject state = JavaAuthManager.toJson(authManager); // Add listener for automatic updates authManager.getChangeListeners().add(() -> { saveToFile(JavaAuthManager.toJson(authManager)); }); // Restore state JavaAuthManager authManager = JavaAuthManager.fromJson(httpClient, savedState); ``` ``` -------------------------------- ### Authenticate Java Edition via Credentials Source: https://context7.com/raphimc/minecraftauth/llms.txt Performs direct authentication using email and password credentials. Note that this method does not support accounts with two-factor authentication enabled. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.CredentialsMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaCredentials; import net.lenni0451.commons.httpclient.HttpClient; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Login using email and password (does not support 2FA) JavaAuthManager authManager = JavaAuthManager.create(httpClient) .login(CredentialsMsaAuthService::new, new MsaCredentials("user@example.com", "password123")); System.out.println("Username: " + authManager.getMinecraftProfile().getUpToDate().getName()); System.out.println("Access token: " + authManager.getMinecraftToken().getUpToDate().getToken()); ``` -------------------------------- ### Migrating Tokens from MinecraftAuth 4.x.x to 5.x.x Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Utilizes the MinecraftAuth4To5Migrator class to facilitate the migration of saved tokens for both Minecraft: Java Edition and Minecraft: Bedrock Edition to the new auth manager structure in version 5.x.x. ```java MinecraftAuth4To5Migrator migrator = new MinecraftAuth4To5Migrator(); migrator.migrateJavaEditionTokens(oldAuthManager, newAuthManager); migrator.migrateBedrockEditionTokens(oldAuthManager, newAuthManager); ``` -------------------------------- ### Bedrock Edition Realms API - List, Accept Invite, and Join Realms Source: https://context7.com/raphimc/minecraftauth/llms.txt Provides Realms API access for Minecraft: Bedrock Edition, including listing realms, accepting invites, and joining servers. It also supports checking client compatibility. Requires an authenticated BedrockAuthManager and an HttpClient. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.bedrock.BedrockAuthManager; import net.raphimc.minecraftauth.extra.realms.service.impl.BedrockRealmsService; import net.raphimc.minecraftauth.extra.realms.model.RealmsServer; import net.raphimc.minecraftauth.extra.realms.model.RealmsJoinInformation; import java.util.List; // After Bedrock authentication BedrockAuthManager authManager = /* ... authenticated manager ... */; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Create Bedrock Realms service BedrockRealmsService realmsService = new BedrockRealmsService( httpClient, "1.20.0", // Latest supported client version authManager.getRealmsXstsToken() ); // Check compatibility if (!realmsService.isCompatible()) { System.out.println("Client version is not compatible with Realms"); return; } // List available realms List realms = realmsService.getWorlds(); for (RealmsServer realm : realms) { System.out.println("Realm: " + realm.getNameOr("Unnamed") + " - " + realm.getState()); } // Accept a realm invite by code RealmsServer invitedRealm = realmsService.acceptInvite("inviteCodeHere"); System.out.println("Accepted invite to: " + invitedRealm.getNameOr("Unnamed")); // Join a realm if (!realms.isEmpty()) { RealmsJoinInformation joinInfo = realmsService.joinWorld(realms.get(0)); System.out.println("Connect to: " + joinInfo.getAddress()); } // Leave an invited realm realmsService.leaveInvitedRealm(invitedRealm); ``` -------------------------------- ### Java Edition Realms API - List and Join Realms Source: https://context7.com/raphimc/minecraftauth/llms.txt Provides access to the Minecraft Realms API for Java Edition. It allows listing available realms, checking client compatibility, and joining a selected realm. Requires an authenticated JavaAuthManager and an HttpClient. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.extra.realms.service.impl.JavaRealmsService; import net.raphimc.minecraftauth.extra.realms.model.RealmsServer; import net.raphimc.minecraftauth.extra.realms.model.RealmsJoinInformation; import net.raphimc.minecraftauth.extra.realms.exception.RealmsRequestException; import java.util.List; // After authentication JavaAuthManager authManager = /* ... authenticated manager ... */; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Create Realms service (requires current game version) JavaRealmsService realmsService = new JavaRealmsService( httpClient, "1.20.4", // Latest supported client version authManager.getMinecraftToken(), authManager.getMinecraftProfile() ); // Check if client version is compatible if (!realmsService.isCompatible()) { System.out.println("Client version is not compatible with Realms"); return; } // List all available realms List realms = realmsService.getWorlds(); for (RealmsServer realm : realms) { System.out.println("Realm: " + realm.getNameOr("Unnamed")); System.out.println(" Owner: " + realm.getOwnerNameOr("Unknown")); System.out.println(" State: " + realm.getState()); System.out.println(" Players: " + realm.getMaxPlayers()); } // Join a realm if (!realms.isEmpty()) { try { RealmsJoinInformation joinInfo = realmsService.joinWorld(realms.get(0)); System.out.println("Connect to: " + joinInfo.getAddress()); } catch (RealmsRequestException e) { if (e.getErrorCode() == RealmsRequestException.ERROR_TOS_NOT_ACCEPTED) { // User must accept Realms Terms of Service System.out.println("Please accept Realms ToS: https://aka.ms/MinecraftRealmsTerms"); realmsService.acceptTos(); // Retry joining after accepting ToS } else { throw e; } } } ``` -------------------------------- ### Bedrock Edition Authentication Source: https://context7.com/raphimc/minecraftauth/llms.txt Details on how to authenticate for Minecraft: Bedrock Edition. This process requires additional parameters such as the game version and session key pairs for encryption. ```APIDOC ## Bedrock Edition Authentication ### Description Provides authentication for Minecraft: Bedrock Edition, which requires additional parameters like game version and session key pairs for encryption. ### Method N/A (Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.bedrock.BedrockAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaDeviceCode; import net.lenni0451.commons.httpclient.HttpClient; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Create Bedrock auth manager with game version BedrockAuthManager authManager = BedrockAuthManager.create(httpClient, "1.20.0") .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Go to: " + deviceCode.getDirectVerificationUri()); }); // Get certificate chain for server connections var certificateChain = authManager.getMinecraftCertificateChain().getUpToDate(); System.out.println("Certificate chain obtained"); // Get multiplayer token var multiplayerToken = authManager.getMinecraftMultiplayerToken().getUpToDate(); System.out.println("Multiplayer token: " + multiplayerToken.getToken()); ``` ### Response N/A (Code Example) ### Response Example N/A (Code Example) ``` -------------------------------- ### Authenticate Java Edition via Device Code Flow Source: https://context7.com/raphimc/minecraftauth/llms.txt Uses the JavaAuthManager to authenticate users via the device code flow. This method is recommended as it supports two-factor authentication and avoids direct credential handling. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.java.JavaAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaDeviceCode; import net.lenni0451.commons.httpclient.HttpClient; import java.util.function.Consumer; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Login using device code flow (recommended) JavaAuthManager authManager = JavaAuthManager.create(httpClient) .login(DeviceCodeMsaAuthService::new, new Consumer() { @Override public void accept(MsaDeviceCode deviceCode) { System.out.println("Go to: " + deviceCode.getVerificationUri()); System.out.println("Enter code: " + deviceCode.getUserCode()); System.out.println("Or go directly to: " + deviceCode.getDirectVerificationUri()); } }); String username = authManager.getMinecraftProfile().getUpToDate().getName(); String accessToken = authManager.getMinecraftToken().getUpToDate().getToken(); System.out.println("Logged in as: " + username); ``` -------------------------------- ### Serialize and Deserialize AuthManager State Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Shows how to convert the JavaAuthManager state to a JSON object for persistent storage and how to restore it later. Includes best practices for attaching change listeners to ensure tokens are saved when updated. ```java // Serialization JsonObject serializedAuthManager = JavaAuthManager.toJson(authManager); // Deserialization JavaAuthManager authManager = JavaAuthManager.fromJson(httpClient, serializedAuthManager); // Attaching listener authManager.getChangeListeners().add(() -> { // save the auth manager state here }); ``` -------------------------------- ### Minecraft Java Edition Login using Device Code Source: https://github.com/raphimc/minecraftauth/blob/main/README.md Implements the device code authentication flow for Minecraft Java Edition. This method is recommended as it supports 2FA and provides a user-friendly verification process via a URL and code. It handles token refreshing automatically. ```java JavaAuthManager authManager = authManagerBuilder.login(DeviceCodeMsaAuthService::new, new Consumer() { @Override public void accept(MsaDeviceCode deviceCode) { // Method to generate a verification URL and a code for the user to enter on that page System.out.println("Go to " + deviceCode.getVerificationUri()); System.out.println("Enter code " + deviceCode.getUserCode()); // There is also a method to generate a direct URL without needing the user to enter a code System.out.println("Go to " + deviceCode.getDirectVerificationUri()); } }); System.out.println("Username: " + authManager.getMinecraftProfile().getUpToDate().getName()); System.out.println("Access token: " + authManager.getMinecraftToken().getUpToDate().getToken()); ``` -------------------------------- ### Bedrock Edition Authentication with Device Code Source: https://context7.com/raphimc/minecraftauth/llms.txt Authenticates the Bedrock Edition of Minecraft using the device code flow. This method requires specifying the game version and involves obtaining certificate chains and multiplayer tokens. It prints the verification URI to the console. ```java import net.raphimc.minecraftauth.MinecraftAuth; import net.raphimc.minecraftauth.bedrock.BedrockAuthManager; import net.raphimc.minecraftauth.msa.service.impl.DeviceCodeMsaAuthService; import net.raphimc.minecraftauth.msa.model.MsaDeviceCode; import net.lenni0451.commons.httpclient.HttpClient; HttpClient httpClient = MinecraftAuth.createHttpClient("MyApp/1.0"); // Create Bedrock auth manager with game version BedrockAuthManager authManager = BedrockAuthManager.create(httpClient, "1.20.0") .login(DeviceCodeMsaAuthService::new, deviceCode -> { System.out.println("Go to: " + deviceCode.getDirectVerificationUri()); }); // Get certificate chain for server connections var certificateChain = authManager.getMinecraftCertificateChain().getUpToDate(); System.out.println("Certificate chain obtained"); // Get multiplayer token var multiplayerToken = authManager.getMinecraftMultiplayerToken().getUpToDate(); System.out.println("Multiplayer token: " + multiplayerToken.getToken()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.