Как узнать свой access token minecraft

Обновлено: 04.07.2024

Здесь приведена информация по авторизации для лаунчеров и серверов Minecraft через сервис авторизации Ely.by.

Протокол авторизации реализован максимально похожим на оригинальный протокол авторизации Mojang, но тем не менее эта документация описывает все доступные функции конкретно сервиса авторизации Ely.by.

Checking Game Ownership

So let's use our mc access token to check if a product licence is attached to the account.

The access token goes into the auth header: Authorization: Bearer <Minecraft Access Token> . (Keep in mind that Bearer is actually the prefix you must include!)

If the account owns the game, the response will look like this:

The first jwts contain the values:

the last jwt looks like this decoded:

If the account doesn't own the game, the items array will be empty.

Note that the signature should always be checked with the public key from Mojang to verify that it is a legitimate response from the official servers:

See the JWT standard[1] for more details.

In case the public key ever changes, it can be extracted from the launcher library:

The created file launcher-strings.txt will include 2 strings which begin with -----BEGIN PUBLIC KEY----- and end with -----END PUBLIC KEY----- . The first key seems to be the one used for the JWT tokens, use of the second key is unknown.

Authenticate

Authenticates a user using their password.

Endpoint

Payload

The clientToken should be a randomly generated identifier and must be identical for each request. The vanilla launcher generates a random (version 4) UUID on first run and saves it, reusing it for every subsequent request. In case it is omitted the server will generate a random token based on Java's UUID.toString() which should then be stored by the client. This will however also invalidate all previously acquired accessToken s for this user across all clients.

Response

Note: If a user wishes to stay logged in on their computer you are strongly advised to store the received accessToken instead of the password itself.

Currently each account will only have one single profile, multiple profiles per account are however planned in the future. If a user attempts to log into a valid Mojang account with no attached Minecraft license, the authentication will be successful, but the response will not contain a selectedProfile field, and the availableProfiles array will be empty.

Some instances in the wild have been observed of Mojang returning a flat null for failed refresh attempts against legacy accounts. It's not clear what the actual error tied to the null response is and it is extremely rare, but implementations should be wary of null output from the response.

This endpoint is severely rate-limited: multiple /authenticate requests for the same account in a short amount of time (think 3 requests in a few seconds), even with the correct password, will eventually lead to an Invalid credentials. response. This error clears up a few seconds later.

Authenticate with Minecraft

Now we can finally start talking to Minecraft. The XSTS token from the last request allows us to authenticate to Minecraft using

This access token allows us to launch the game, but, we haven't actually checked if the account owns the game. Everything until here works with a normal Microsoft account!

Одиночная игра¶

По сути, одиночная игра - это локальный сервер, созданный для одного игрока. По крайней мере это так, начиная с версии 1.6, в которой и был представлен механизм локальных серверов.

Тем не менее, описанный ниже запрос актуален только для Minecraft 1.7.6+, когда для загрузки скинов стала использоваться так же Authlib.

Запрос на этот URL выполняется клиентом в одиночной игре на локальном сервере (созданном посредством самой игры). В URL передаётся UUID пользователя, с которым был запущен клиент, а в ответ получается информация о текстурах игрока в таком же формате, как и при hasJoined запросе.

Microsoft Authentication Scheme

There are multiple steps and different tokens required, but in the end, you get a normal Minecraft token back. Launching the game itself hasn't changed.

Refreshing Tokens

You can use the refresh_token you got in the previous request to acquire a new access_token. Just call the same endpoint as before, switching out code for the refresh token and grant type authorization_code for refresh_token

(the response is the same as for requesting tokens with a code)

Установка на версии ниже 1.7.2¶

Для более старых версий существует достаточно большое многообразие различных случаев, раскрыть которые в этой документации не представляется возможным. Вся установка заключается в замене определённых строк в определённых классах через InClassTranslator.

На форуме RuBukkit есть отличный пост, в котором собрана вся нужна информация по именам классов на различных версиях Minecraft. Переписывать его сюда не имеет смысла, так что просто перейдите на его страницу и найдите нужную версию.

Пример установки¶

Предположим, что вы хотите установить авторизацию на сервер версии 1.5.2.

Сначала вы переходите по вышеприведённой ссылке, выбираете нужную версию (1.5.2) и видите список классов:

bdk.class - путь до joinserver

jg.class - путь до checkserver

Затем вы должны взять .jar файл клиента и открыть его любым архиватором. После чего вам необходимо найти файл bdk.class. Для этого удобно воспользоваться поиском.

После того, как вы нашли файл, его нужно извлечь из архива - просто перетащите его оттуда в удобную для вас дирикторию.

Дальше запустите InClassTranslator и в нём откройте этот класс. Слева будет список найденных в файле строк, которые вы можете изменить. Нужно заменить только строку, отвечающую за запрос на подключение к серверу:

Порядок редактирования: выбрать нужную строку, изменить, сохранить.

После этого вам нужно положить изменённый .class обратно в .jar файл игры.

Ту же самую операцию вам необходимо провести и с сервером, только заменить ссылку на hasJoined.

Validate

Checks if an accessToken is usable for authentication with a Minecraft server. The Minecraft Launcher (as of version 1.6.13) calls this endpoint on startup to verify that its saved token is still usable, and calls /refresh if this returns an error.

Note that an accessToken may be unusable for authentication with a Minecraft server, but still be good enough for /refresh . This mainly happens when one has used another client (e.g. played Minecraft on another PC with the same account). It seems only the most recently obtained accessToken for a given account can reliably be used for authentication (the next-to-last token also seems to remain valid, but don't rely on it).

/validate may be called with or without a clientToken . If a clientToken is provided, it should match the one used to obtain the accessToken . The Minecraft Launcher does send a clientToken to /validate .

Endpoint

Payload

Response

Returns an empty payload ( 204 No Content ) if successful, an error JSON with status 403 Forbidden otherwise.

Общие положения¶

При успешном запросе, сервер вернёт ответ со статусом 200. Любой другой код свидетельствует об ошибке.

В случае стандартной ошибки, вы получите следующие данные:

Предусмотренные ошибки¶

В отличие от оригинального протокола, на Ely применяется меньший зоопарк ошибок:

Вы передали неполный список данных для выполнения запроса.

Внимательно перепроверьте что вы шлёте в запросе и что указано в документации.

Пользователь ввёл/разработчик передал неверные значения.

Необходимо вывести пользователю уведомление о неправильно введённых данных.

Для индикации ошибки Not Found используется ответ с 404 статусом.

Готовые библиотеки authlib¶

Ely.by поддерживает библиотеку authlib-injector. Это наиболее простой и универсальный способ установки системы авторизации в игру и игровые сервера. За подробностями обратитесь в соответствующий раздел документации .

Поскольку самостоятельная реализация связана с трудностями поиска исходников, подключения зависимостей и в конце-концов с процессом компиляции, на странице загрузок нашей системы скинов вы можете загрузить уже готовые библиотеки со всеми необходимыми изменениями. Выберите в выпадающем списке необходимую версию и следуйте инструкции по установке, размещённой на той же странице ниже.

В более ранних версиях игры система скинов находилась внутри игрового клиента, так что библиотеки ниже обеспечивают лишь авторизацию:

Для установки вам необходимо заменить оригинальную библиотеку, располагающуюся по пути <директория установки minecraft>/libraries/com/mojang/authlib/ . Убедитесь в том, что версии скачанного и заменяемого файлов совпадают.

Authenticate with XSTS

Now that we are authenticated with XBL, we need to get a XSTS token, we can use to login to Minecraft.

Again, set content type and accept to json.

Response will look like this:

The endpoint can return a 401 error with the below response:

The Redirect parameter usually will not resolve or go anywhere in a browser, likely they're targeting Xbox consoles.

Noted XErr codes and their meanings:

Установка authlib на сервер¶

Сервер также использует authlib для выполнения авторизации игрока, поэтому соответствующие изменения должны быть также применены и к нему. Ниже приведены инструкции по установки authlib для различных реализаций сервера Minecraft.

Если ни одна из приведённых ниже инструкций не подошла для вашей реализации сервера, пожалуйста, создайте новый issue и мы допишем инструкцию для вашего сервера.

Оригинальный сервер¶

С помощью архиватора откройте файл сервера minecraft_server.ВЕРСИЯ.jar . Таким же образом откройте архив с authlib для соответствующей версии сервера. Перед вами будет два окна: одно с файлами сервера, другое с файлами authlib. Вам необходимо «перетащить» из архива с authlib все файлы и папки, за исключением директории META-INF, и подтвердить замену.

Процесс установки Authlib

Обратите внимание: «перетягивать» содержимое нужно ниже папок сервера (в область файлов .class). ¶

После этих действий вы можете закрыть оба окна и в файле server.properties установить значение online-mode=true .

Bukkit/Spigot¶

Сперва выполните установку, как она описана для оригинального сервера. Затем скачайте библиотеки commons-io и commons-lang3, после чего аналогичным с authlib образом последовательно переместите содержимое скачанных архивов в файлы сервера.

Forge/Sponge¶

Прежде чем производить установку, необходимо определить, какой именно файл подлежит модификации:

>=1.16: libraries/net/minecraft/server/ВЕРСИЯ-ЦИФРЫ/server-ВЕРСИЯ-ЦИФРЫ-extra.jar .

1.13-1.15: libraries/net/minecraft/server/ВЕРСИЯ/server-ВЕРСИЯ-extra.jar .

<=1.12: minecraft_server.ВЕРСИЯ.jar .

Когда необходимый файл найден, выполните для него установку authlib, аналогично оригинальному серверу.

Paper (PaperSpigot)¶

Установка производится по аналогии с Bukkit/Spigot в файл cache/patched-ВЕРСИЯ.jar . После внесения изменений, запускать сервер нужно через jar-файл из директории cache , поскольку в противном случае Paper восстановит исходное состояние файла:

Request format

All requests to Yggdrasil are made to the following server:

Further, they are expected to fulfill the following rules:

  • Are POST requests
  • Have the Content-Type header set to application/json
  • Contain a JSON-encoded dictionary as payload

If a request was successful the server will respond with:

  • A successful status code 2XX
  • An empty payload or a JSON-encoded dictionary according to the specifications below

If however a request fails, the server will respond with:

Authentication

Minecraft 1.6 introduced a new authentication scheme called Yggdrasil which completely replaces the previous authentication system. Mojang's other game, Scrolls, uses this method of authentication as well. Mojang has said that this authentication system should be used by everyone for custom logins, but credentials should never be collected from users. For newer Microsoft accounts, see Microsoft Authentication Scheme.

Authorization Code -> Authorization Token

The next step is to get an access token from the auth code. This isn't done in the browser for security reasons.

This exchange should be done on the server-side as it requires the use of your client secret which, as the name implies, should be kept secret.

Don't forget to set Content-Type: application/x-www-form-urlencoded

The response will look like this:

We care about the access_token here.

Microsoft OAuth Flow


Prior to any of these steps, you will first need to obtain an OAuth 2.0 Client ID & secret by creating a Microsoft Azure application.

In the first step, we are logging into the Microsoft account. This has to be done in a browser/webview!

The URL generated, either manually, or through an OAuth2 library, would look something like this:

Note: If using the MSAL library to handle OAuth for you, you must use the consumers AAD tenant to sign in with the XboxLive.signin scope. Using an Azure AD tenant ID or the common scope will just give errors. This also means you cannot sign in with users that are in the AAD tenant, only with consumer Microsoft accounts.

The user will be prompted to enter a username (E-Mail, Skype ID, Phone number, whatever) and their password. If those are valid, the user will be redirected. The user doesn't need to own MC, that check comes way later!

The redirect will look something like this

You have to extract the code param, it's your Microsoft Authorization Code.

Авторизация в лаунчере¶

В этом разделе описана авторизация для игрового лаунчера и описывает действия, необходимые для получения accessToken для игрового клиента Minecraft. В результате авторизации будет получен JWT-токен с правами доступа minecraft_server_session .

Мы рекомендуем использовать протокол авторизации OAuth 2.0 с запросом прав доступа minecraft_server_session , как более безопасный и удобный для пользователя метод.

Непосредственная авторизация пользователя, используя его логин (ник или E‑mail), пароль и токен двухфакторной аутентификации.

username (string) – Никнейм пользователя или его E‑mail (более предпочтительно).

password (string) – Пароль пользователя или комбинация пароль:токен .

clientToken (string) – Уникальный токен лаунчера пользователя.

requestUser (bool) – Если поле передано как true , то в ответе сервера будет присутствовать поле user .

Система аккаунтов Ely.by поддерживает защиту пользователей посредством двухфакторной аутентификации. В оригинальном протоколе авторизации Mojang не предусмотрено возможности для передачи TOTP-токенов. Для решения этой проблемы и сохранения совместимости с реализацией сервера Yggdrasil, мы предлагаем передавать токен в поле password в формате пароль:токен .

К сожалению, не все пользователи осведомлены об этой возможности, поэтому будет лучше при получении ошибки о защищённости аккаунта пользователя двухфакторной аутентификацией явно запросить у него токен и склеить его программно.

Если пользователь указал верные логин и пароль, но для его аккаунта включена двухфакторная аутентификация, вы получите ответ с 401 статусом и следующим содержимым:

При получении этой ошибки, необходимо запросить у пользователя ввод TOTP‑токена, после чего повторить запрос на авторизацию с теми же учётными данными, добавив к паролю постфикс в виде :токен , где токен — это значение, введённое пользователем.

Если пароль пользователя был «password123», а токен «123456», то после склейки поле password примет значение «password123:123456».

Если в результате этих действий вы получите ответ с 401 статутом и errorMessage «Invalid credentials. Invalid email or password.», то это будет свидетельствовать о том, что переданный токен неверен и его нужно перезапросить у пользователя.

Если все данные будут переданы верно, вы получите следующий ответ:

Обновляет валидный accessToken . Этот запрос позволяет не хранить на клиенте его пароль, а оперировать только сохранённым значением accessToken для практически бесконечной возможности проходить авторизацию.

accessToken (string) – Уникальный ключ, полученный после авторизации.

clientToken (string) – Уникальный идентификатор клиента, относительно которого получен accessToken.

requestUser (bool) – Если поле передано как true , то в ответе сервера будет присутствовать поле user .

В оригинальном протоколе так же передаётся значение selectedProfile , но в реализации Mojang он не влияет ни на что. Наша реализация сервера авторизации игнорирует этот параметр и опирается на значения accessToken и clientToken .

В случае получения какой-либо предусмотренной ошибки, следует заново запросить пароль пользователя и произвести обычную авторизацию.

Этот запрос позволяет проверить валиден ли указанный accessToken или нет. Этот запрос не обновляет токен и его время жизни, а только позволяет удостовериться, что он ещё действительный.

accessToken (string) – Токен доступа, полученный после авторизации.

Успешным ответом будет являться пустое тело. При ошибке будет получен 400 или 401 статус. Пример ответа сервера при отправке истёкшего токена:

Этот запрос позволяет выполнить инвалидацию всех выданных пользователю токенов.

username (string) – Никнейм пользователя или его E-mail (более предпочтительно).

password (string) – Пароль пользователя.

Успешным ответом будет являться пустое тело. Ориентируйтесь на поле error в теле ответа.

Запрос позволяет инвалидировать accessToken. В случае, если переданный токен не удастся найти в хранилище токенов, ошибка не будет сгенерирована и вы получите успешный ответ.

accessToken (string) – Уникальный ключ, полученный после авторизации.

clientToken (string) – Уникальный идентификатор клиента, относительно которого получен accessToken.

Успешным ответом будет являться пустое тело. Ориентируйтесь на поле error в теле ответа.

Авторизация на сервере¶

Эти запросы выполняются непосредственно клиентом и сервером при помощи внутреннего кода или библиотеки authlib (начиная с версии 1.7.2). Они актуальны только в том случае, если вы уже произвели авторизацию и запустили игру с валидным accessToken. Вам остаётся только заменить пути внутри игры/библиотеки на приведённые ниже пути.

Поскольку непосредственно изменить что-либо в работе authlib или игры вы не можете, здесь не приводятся передаваемые значения и ответы сервера. При необходимости вы сможете найти эту информацию самостоятельно в интернете.

Через authlib¶

Эта часть документации описывает запросы, выполняемые через authlib в версии игры 1.7.2+. Для более старых версий смотрите раздел ниже.

Все запросы из этой категории выполняются на подуровень /session. Перед каждым из запросов указан тип отправляемого запроса.

Запрос на этот URL производится клиентом в момент подключения к серверу с online-mode=true.

Запрос на этот URL выполняет сервер с online-mode=true после того, как клиент, пытающийся к нему подключится, успешно выполнит join запрос.

Внутри тела ответа есть параметр properties, который, в свою очередь, содержит поле value с закодированной в ней base64 строкой. В оригинальной системе авторизации данные зашифрованы с помощью приватного ключа и расшифровывались на клиенте с помощью публичного. Ely, в свою очередь, не выполняет шифрацию вовсе, поэтому вам необходимо отключить проверку подписи в библиотеке authlib. В противном случае текстуры всегда будут признаваться невалидными.

Для старых версий¶

Эта часть документации описывает запросы, выполняемые более старыми версиями Minecraft, когда не применялась библиотека authlib. Это все версии, младше версии 1.7.2.

Все запросы из этой категории выполняются на подуровень /session/legacy. Перед каждым из запросов указан тип отправляемого запроса.

Принцип обработки этих запросов такой же, как и для authlib, отличие только во входных параметрах и возвращаемых значения.

Запрос на этот URL производится клиентом в момент подключения к серверу с online-mode=true.

Запрос на этот URL выполняет сервер с online-mode=true после того, как клиент, пытающийся к нему подключится, успешно выполнит join запрос.

BungeeCord¶

Вы можете воспользоваться библиотекой authlib-injector для установки системы авторизации без модификации внутренностей сервера.

Хотя BungeeCord и является проксирующим сервером, авторизацию игроков он выполняет самостоятельно. К сожалению, BungeeCord не опирается на использование Authlib, а реализует процесс авторизации самостоятельно, поэтому для установки системы авторизации Ely.by вам понадобится модифицировать скомпилированные .class файлы.

Для установки следуйте инструкции ниже:

Скачайте программу InClassTranslator (прямых ссылок не даём, но его легко найти).

С помощью архиватора откройте файл BungeeCord.jar .

Перейдите по пути net/md_5/bungee/connection и найдите там файл InitialHandler.class (без каких-либо символов $).

Распакуйте этот файл. В самом простом случае сделать это можно просто «вытянув» его из окна архиватора.

Редактирование в InClassTranslator

Сохраните изменения и перетащите измененный файл обратно в архив сервера. Подтвердите замену.

Перетаскивание отредактированного файла назад в архив

После выполнения этих действий вы можете указать в файле конфигурации BungeeCord ( config.yml ) значение online_mode=true .

Мы также рекомендуем выполнить установку Authlib на все сервера позади BungeeCord. Это может быть необходимо для плагинов, которые используют API Mojang. Инструкция по установке на конечные сервера приведена выше.

При этом все сервера должны иметь в своей конфигурации ( server.properties ) значение online-mode=false , поскольку пользователи уже авторизованы силами BungeeCord.

Sample Implementations

There is a rough sample implementation in Java (using javafx and its webview) here.

Как узнать свой access token minecraft

A simple, open and documented Java API for Minecraft authentication.

  • Works with both Mojang and old Minecraft accounts
  • Provides methods for every endpoint
  • Custom exceptions for error reporting

Just add this to your build.gradle :

The library uses mainly static methods. You won't have to instantiate anything. Just call the static methods in the class OpenMCAuthenticator with the required arguments to get your response.

authenticate and refresh return a response object extending LoginResponse ( AuthenticationResponse or RefreshResponse ). This means, regardless of the method used, you will be able to use the following methods:

  • getAccessToken - returns the access token to be used when launching the game
  • getClientToken - returns the client token used in the request
  • getSelectedProfile - returns a Profile object representing the current profile

For a more detailed documentation, just check the javadoc included with the library.

The Profile object is returned by loginResponse.getSelectedProfile() and a Profile[] object is returned by authenticationResponse.getAvailableProfiles() (where loginResponse and authenticationResponse are instances of the two classes). It contains the following (non-static) methods:

  • getUUID() - returns the user's UUID. Can be converted to a string with toString()
  • getName() - returns the nickname of the user with correct capitalization as a String
  • isLegacy() - returns a boolean; true if the profile is a legacy (old) Minecraft account (uses username to log in)

Every available method throws an exception extending RequestException if the request returned an authentication problem. The full list of exceptions is available below.

  • RequestException - a general exception. Every other authentication exception extends this. To get more detailed info about the exception, call getError() or getErrorMessage() .
  • InvalidCredentialsException - the provided credentials are invalid (bad or empty username/password). Thrown by authenticate and signout .
  • InvalidTokenException - the provided token is invalid. Thrown by refresh , validate and invalidate .
  • UserMigratedException - the Mojang account email address should be used as the username instead of the nickname. Thrown by authenticate and signout .
  • AuthenticationUnavailableException - thrown every time an IOException is generated, so every time the authentication services are unavailable. Does not extend RequestException as there's no error code.

Use OpenMCAuthenticator.authenticate to request authentication with an username and a password.

Use OpenMCAuthenticator.refresh to request a new token by providing a valid one and the client token used to get the token in the first place. The token has to be the same to the one returned when getting the access token! See the Client tokens section for more info.

Use OpenMCAuthenticator.validate to check if the provided access token represents the latest active session. This will return true only if the token is the most recently generated. It's intended to be used by servers to check if the player is not logged in elsewhere with a new access token.

Use OpenMCAuthenticator.invalidate to invalidate the given access token. The client token has to be the same to the one returned when getting the access token! See the Client tokens section for more info.

Use OpenMCAuthenticator.signout to invalidate every access token for an user by providing its username and password.

The clientToken value is intended to be generated randomly for authenticate , signout and validate (while request and invalidate require it to be the same to the one received when getting the token)

OpenMCAuthenticator by default doesn't send a client token when optional, as the authentication servers automatically generate one (by default a random UUID, which is then obtainable by the client by calling getClientToken() on the returned LoginResponse ). If for some reason you need to use a custom client token, just add it as a String to the request method parameters. For example:

If you found an issue in the API, just click here to report it! Try to be as accurate as possible and add some steps to reproduce the issue.

Errors

These are some of the errors that can be encountered:

Error Cause Error message Notes
Method Not Allowed The method specified in the request is not allowed for the resource identified by the request URI Something other than a POST request was received.
Not Found The server has not found anything matching the request URI Non-existing endpoint was called.
ForbiddenOperationException UserMigratedException Invalid credentials. Account migrated, use email as username.
ForbiddenOperationException Invalid credentials. Invalid username or password.
ForbiddenOperationException Invalid credentials. Too many login attempts with this username recently (see /authenticate ). Note that username and password may still be valid!
ForbiddenOperationException Invalid token. accessToken was invalid.
ForbiddenOperationException Token does not exist. accessToken was used in another session that was issued AFTER this session.
IllegalArgumentException Access token already has a profile assigned. Selecting profiles isn't implemented yet.
IllegalArgumentException credentials is null Username/password was not submitted.
IllegalArgumentException Invalid salt version .
Unsupported Media Type The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method Data was not submitted as application/json
ResourceException Gone (410) - The requested resource is no longer available at the server and no forwarding address is known Account was migrated to Microsoft account

Authenticate with XBL

Now that we are authenticated with Microsoft, we can authenticate to Xbox Live.

To do that, we send

Again, it will complain if you don't set Content-Type: application/json and Accept: application/json

The response will look like this:

We need to save token and userhash.

Refresh

Refreshes a valid accessToken . It can be used to keep a user logged in between gaming sessions and is preferred over storing the user's password in a file (see lastlogin).

Endpoint

Payload

Note: The provided accessToken gets invalidated.

Response

Contents

Get the profile

Now that we know that the account owns the game, we can get their profile in order to fetch the UUID:

Again, the access token goes into the auth header: Authorization: Bearer token

The response will look like this, if the account owns the game:

Else it will look like this:

You should know have all necessary data (the mc access token, the username and the uuid) to launch the game. Well done!

Contents

Читайте также: