Skip to content

Authentication manager

Authentication Manager

Authenticate with Windows Live Server and Xbox Live.

pythonxbox.authentication.manager.log = logging.getLogger('authentication') module-attribute

pythonxbox.authentication.manager.DEFAULT_SCOPES = ['Xboxlive.signin', 'Xboxlive.offline_access'] module-attribute

pythonxbox.authentication.manager.AuthenticationManager(client_session, client_id, client_secret, redirect_uri, scopes=None)

Source code in src/pythonxbox/authentication/manager.py
def __init__(
    self,
    client_session: SignedSession | httpx.AsyncClient,
    client_id: str,
    client_secret: str,
    redirect_uri: str,
    scopes: list[str] | None = None,
) -> None:
    self.session = client_session
    self._client_id = client_id
    self._client_secret = client_secret
    self._redirect_uri = redirect_uri
    self._scopes = scopes or DEFAULT_SCOPES

oauth = None class-attribute instance-attribute

user_token = None class-attribute instance-attribute

xsts_token = None class-attribute instance-attribute

session = client_session instance-attribute

generate_authorization_url(state=None)

Generate Windows Live Authorization URL.

Source code in src/pythonxbox/authentication/manager.py
def generate_authorization_url(self, state: str | None = None) -> str:
    """Generate Windows Live Authorization URL."""
    query_params = {
        "client_id": self._client_id,
        "response_type": "code",
        "approval_prompt": "auto",
        "scope": " ".join(self._scopes),
        "redirect_uri": self._redirect_uri,
    }

    if state:
        query_params["state"] = state

    return str(
        httpx.URL(
            "https://login.live.com/oauth20_authorize.srf", params=query_params
        )
    )

request_tokens(authorization_code) async

Request all tokens.

Source code in src/pythonxbox/authentication/manager.py
async def request_tokens(self, authorization_code: str) -> None:
    """Request all tokens."""
    self.oauth = await self.request_oauth_token(authorization_code)
    self.user_token = await self.request_user_token()
    self.xsts_token = await self.request_xsts_token()

refresh_tokens() async

Refresh all tokens.

Source code in src/pythonxbox/authentication/manager.py
async def refresh_tokens(self) -> None:
    """Refresh all tokens."""
    if not (self.oauth and self.oauth.is_valid()):
        self.oauth = await self.refresh_oauth_token()
    if not (self.user_token and self.user_token.is_valid()):
        self.user_token = await self.request_user_token()
    if not (self.xsts_token and self.xsts_token.is_valid()):
        self.xsts_token = await self.request_xsts_token()

request_oauth_token(authorization_code) async

Request OAuth2 token.

Source code in src/pythonxbox/authentication/manager.py
async def request_oauth_token(self, authorization_code: str) -> OAuth2TokenResponse:
    """Request OAuth2 token."""
    return await self._oauth2_token_request(
        {
            "grant_type": "authorization_code",
            "code": authorization_code,
            "scope": " ".join(self._scopes),
            "redirect_uri": self._redirect_uri,
        }
    )

refresh_oauth_token() async

Refresh OAuth2 token.

Source code in src/pythonxbox/authentication/manager.py
async def refresh_oauth_token(self) -> OAuth2TokenResponse:
    """Refresh OAuth2 token."""
    return await self._oauth2_token_request(
        {
            "grant_type": "refresh_token",
            "scope": " ".join(self._scopes),
            "refresh_token": self.oauth.refresh_token,
        }
    )

request_user_token(relying_party='http://auth.xboxlive.com', use_compact_ticket=False) async

Authenticate via access token and receive user token.

Source code in src/pythonxbox/authentication/manager.py
async def request_user_token(
    self,
    relying_party: str = "http://auth.xboxlive.com",
    use_compact_ticket: bool = False,
) -> XAUResponse:
    """Authenticate via access token and receive user token."""
    url = "https://user.auth.xboxlive.com/user/authenticate"
    headers = {"x-xbl-contract-version": "1"}
    data = {
        "RelyingParty": relying_party,
        "TokenType": "JWT",
        "Properties": {
            "AuthMethod": "RPS",
            "SiteName": "user.auth.xboxlive.com",
            "RpsTicket": self.oauth.access_token
            if use_compact_ticket
            else f"d={self.oauth.access_token}",
        },
    }

    resp = await self.session.post(url, json=data, headers=headers)
    resp.raise_for_status()
    return XAUResponse.model_validate_json(resp.text)

request_xsts_token(relying_party='http://xboxlive.com') async

Authorize via user token and receive final X token.

Source code in src/pythonxbox/authentication/manager.py
async def request_xsts_token(
    self, relying_party: str = "http://xboxlive.com"
) -> XSTSResponse:
    """Authorize via user token and receive final X token."""
    url = "https://xsts.auth.xboxlive.com/xsts/authorize"
    headers = {"x-xbl-contract-version": "1"}
    data = {
        "RelyingParty": relying_party,
        "TokenType": "JWT",
        "Properties": {
            "UserTokens": [self.user_token.token],
            "SandboxId": "RETAIL",
        },
    }

    resp = await self.session.post(url, json=data, headers=headers)
    if resp.status_code == HTTPStatus.UNAUTHORIZED:  # if unauthorized
        msg = (
            "Failed to authorize you! Your password or username may be wrong or"
            " you are trying to use child account (< 18 years old)"
        )
        raise AuthenticationException(msg)
    resp.raise_for_status()
    return XSTSResponse.model_validate_json(resp.text)