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

使用Python+Flask调用Azure DevOps OAuth2.0接口无法获取Token

问题:使用Python Flask对接Azure DevOps OAuth2无法获取Access Token

我尝试通过OAuth2访问Azure DevOps API查询工作项,但无法获取access token。使用Python + Flask开发,实现逻辑参考了微软官方OAuth文档和第三方OAuth教程(后者在对接GitHub时正常,但对接Azure时失效)。

相关依赖库

from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for

配置参数

client_id = "..."
client_secret = "..."
authorization_base_url = "https://app.vssps.visualstudio.com/oauth2/authorize"
token_url = "https://app.vssps.visualstudio.com/oauth2/token"
callback_url = "..."

步骤1:用户授权(运行正常)

@app.route("/")
def demo():
    azure = OAuth2Session(client_id)
    authorization_url, state = azure.authorization_url(authorization_base_url)

    session['oauth_state'] = state
    authorization_url += "&scope=" + authorized_scopes + "&redirect_uri=" + callback_url
    print(authorization_url)
    return redirect(authorization_url)

步骤2:获取access token(触发错误)

@app.route("/callback", methods=["GET"])
def callback():

    fetch_body = "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \
                 "&client_assertion=" + client_secret + \
                 "&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
                 "&assertion=" + request.args["code"] + \
                 "&redirect_uri=" + callback_url

    azure = OAuth2Session(client_id, state=session['oauth_state'])

    token = azure.fetch_token(token_url=token_url, client_secret=client_secret,
                               body=fetch_body,
                               authorization_response=request.url)
    azure.request()

    session['oauth_token'] = token

    return redirect(url_for('.profile'))

错误详情

应用注册及临时SSL证书配置均正常,用Postman发起带client_assertion的请求能正常收到Azure响应,但代码执行时抛出错误:

oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.

排查发现生成的请求体中grant_type被重复添加:

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
grant_type=authorization_code

Azure期望第一个值,但第二个值由requests-oauthlib库自动生成。尝试显式指定grant_type:

token = azure.fetch_token(token_url=token_url, client_secret=client_secret,
                           body=fetch_body, grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer",
                           authorization_response=request.url)

又触发新错误:

TypeError: prepare_token_request() got multiple values for argument 'grant_type'

此时请求甚至未发送到Azure。查看oauth2_session.py依赖的web_application.py文件,发现grant_type被固定设置为'authorization_code',因此怀疑该库与Azure OAuth2存在兼容性问题。

请问:

  1. 该库与Azure OAuth2的兼容性问题是否确实存在?
  2. 若存在,使用Python(Flask)对接Azure OAuth2的最简方案是什么?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:51:20