oauth2.0 如何将授权码兑换为访问令牌

fslejnso  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(215)

我正在使用microsoft oauth2工作流,该工作流首先让用户登录到门户,授予“兑换”访问令牌的授权代码,而我在兑换部分遇到了问题。
该脚本首先打开一个浏览器到一个URL,该URL将该授权代码发送到本地Web服务器,该服务器接受该代码并向Microsoft端点发送另一个请求,该端点返回错误消息:The request body must contain the following parameter: 'grant_type'.
快速假设:我的应用程序已正确注册和配置,重定向uri已正确添加

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")
endpoint = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token?client_id={}&scope={}&code={}&redirect_uri={}&grant_type=authorization_code".format(
        client_id, # client id
        "XboxLive.signin", # scope
        activationCode, # code
        redirect_uri, # redirect uri
    )

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

print(res.json())
ryevplcw

ryevplcw1#

第二个请求必须是POST,因此将请求主体中的以下参数发送到令牌端点:

endpoint = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"

body = {
  "client_id": myclient, 
  "client_secret": mysecret,
  "code": mycode,
  "redirect_uri": myredirecturi,
  "grant_type": "authorization_code"}

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

相关问题