如何获取并正确填充Xbox Live REST API的身份验证请求头?
一、用xbox-webapi-python快速实现
这个库已经封装了所有认证流程,对你这种新手最友好,步骤如下:
- 先安装库(直接用pip比手动装仓库更省心)
pip install xbox-webapi
- 编写认证代码,这个代码会引导你完成微软账号登录:
from xbox.webapi.authentication.manager import AuthenticationManager from xbox.webapi.common.exceptions import AuthenticationException # 初始化认证管理器,采用设备流认证(适合桌面/控制台应用场景) auth_mgr = AuthenticationManager() try: # 启动设备流,获取认证所需的验证信息 device_code = auth_mgr.initiate_device_flow() print(f"请打开以下链接并输入代码:{device_code.verification_uri}") print(f"验证代码:{device_code.user_code}") # 等待用户完成登录,获取认证凭证 auth_mgr.authenticate_device_flow(device_code) # 从凭证中提取所需的userhash和token userhash = auth_mgr.userinfo.userhash xsts_token = auth_mgr.xsts_token.token # 组装符合要求的Authorization请求头 auth_header = f"XBL3.0 x={userhash};{xsts_token}" print(f"生成的Authorization头:{auth_header}") except AuthenticationException as e: print(f"认证失败:{e}")
- 运行代码后,按照提示打开网页输入验证代码,登录和Xbox绑定的微软账号,程序就会输出你需要的Authorization头。
二、手动通过微软OAuth 2.0流程获取(适合理解底层逻辑)
如果想自己实现认证流程,步骤会复杂些,但能更清楚原理:
- 第一步:在Azure Active Directory注册一个应用,获取客户端ID(调用Xbox API需要合法的应用身份)
- 第二步:引导用户访问微软授权端点,获取授权码,授权范围需包含
XboxLive.signin XboxLive.offline_access - 第三步:用授权码换取微软的access token和refresh token
- 第四步:把微软的access token发送到Xbox的
https://user.auth.xboxlive.com/user/authenticate端点,获取Xbox用户令牌(user_token) - 第五步:用user_token发送到
https://xsts.auth.xboxlive.com/xsts/authorize端点,获取XSTS token和userhash - 最后:组装成
XBL3.0 x=<userhash>;<xsts_token>的格式
这种方法需要处理多个HTTP请求,对新手不太友好,但如果想深入理解认证流程可以尝试。
内容的提问来源于stack exchange,提问作者Michael Feldman
相关产品推荐
相关产品推荐

