You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何兑换Authorization Code获取Access Token?微软OAuth2流程问题求助

问题分析

错误The request body must contain the following parameter: 'grant_type'.的核心原因是:微软OAuth2的token端点要求所有请求参数(包括grant_type)必须放在POST请求的请求体中,而非拼接在URL的查询字符串里。你的代码当前把所有参数都加到了URL上,导致端点无法识别到grant_type参数。

修复后的代码

修改获取access token的部分,将参数从URL转移到POST请求的data参数中:

import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

import requests


class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("Thanks for logging in!", "utf-8"))
        self.server.code = self.path.split("=")[1]
        self.server.stop = True

        global activationCode
        activationCode = self.server.code

client_id = "client id here"
redirect_uri = "http://localhost:8080"

endpoint = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id={}&response_type=code&redirect_uri={}&response_mode=query&scope={}&state={}".format(
        client_id, # client id
        redirect_uri, # redirect uri
        "XboxLive.signin", # scope
        "12345", # state
    )


global activationCode
activationCode = None
httpServer = HTTPServer(("localhost", 8080), RequestHandler)

webbrowser.open(endpoint)

while not activationCode:
    httpServer.handle_request()

print("Got activation code")

print("Fetching access token")
# 修正:将参数移到请求体,URL仅保留端点地址
token_endpoint = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
payload = {
    "client_id": client_id,
    "scope": "XboxLive.signin",
    "code": activationCode,
    "redirect_uri": redirect_uri,
    "grant_type": "authorization_code"
}

res = requests.post(token_endpoint, data=payload, headers={
    "Content-Type": "application/x-www-form-urlencoded"
})

print(res.json())
关键修改点
  • 单独定义token端点URL,不再拼接参数
  • 创建payload字典存储所有请求参数
  • 使用requests.post的data参数传递payload,确保参数被放入请求体中

修改后微软的token端点就能正确识别所有必填参数,返回有效的access token。

内容的提问来源于stack exchange,提问作者Pilot1782

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:15:22