AuthenticationΒΆ

The basic method allows you to easily retrieve information about users and Mojang games, but you might want to go further by authenticating to your minecraft account. To do so you must first create a MojangAuthenticationApp, this app will then allow you to authenticate to your account.

>>> import mojang
>>> CLIENT_ID = ... # This is your Azure client id
>>> CLIENT_SECRET = ... # This is your Azure client secret
>>> app = mojang.app(CLIENT_ID, CLIENT_SECRET)

After creating your app you can use the get_session() method, which will return a MicrosoftAuthenticatedUser.

>>> # First you must visit the url given by: `app.authorization_url`
>>> # this will redirect you to a url with a code parameter
>>> # you can then use this code to get a session
>>> app.get_session('here goes the code')
MicrosoftAuthenticatedUser(
    name='PLAYER_NAME',
    uuid='PLAYER_UUID',
    is_legacy=False,
    is_demo=False,
    names=(NameInfo(name='PLAYER_NAME', changed_to_at=None),),
    skin=Skin(source='http://...', variant='classic'),
    cape=None,
    created_at=datetime.datetime(2006, 4, 29, 10, 10, 10),
    name_change_allowed=True
)

Here is a full example, you can find the source code on github.

import os

from dotenv import load_dotenv
from flask import Flask, jsonify, redirect, request

import mojang
import mojang.exceptions

load_dotenv()

app = Flask(__name__)
auth_app = mojang.app(
    os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"), "http://localhost:3000"
)


def _sess_to_json(sess):
    return {
        "name": sess.name,
        "uuid": sess.uuid,
        "is_legacy": sess.is_legacy,
        "is_demo": sess.is_demo,
        "names": [{"name": name[0], "changed_to_at": name[1]} for name in sess.names],
        "skin": {
            "url": sess.skin.source if sess.skin else None,
            "variant": sess.skin.variant if sess.skin else None,
        },
        "cape": {"url": sess.cape.source if sess.cape else None},
        "created_at": sess.created_at,
        "can_change_name": sess.name_change_allowed,
    }


@app.route("/")
def index():
    if request.args.get("code", False):
        try:
            sess = auth_app.get_session(request.args["code"])
            return jsonify(_sess_to_json(sess))
        except mojang.exceptions.MicrosoftInvalidGrant:
            pass

    return redirect(auth_app.authorization_url)


if __name__ == "__main__":
    app.run(debug=True, port=3000)