在Python中使用OAuth2.0时无法检索授权代码

piwo6bdm  于 9个月前  发布在  Python
关注(0)|答案(1)|浏览(134)

我正在尝试对公共FHIR服务器进行API调用(SMART Health IT)。我已经托管了我的应用程序(前端)在服务器上使用ngrok,我想在从FHIR检索所需数据之前获取其授权代码和访问令牌。我正在使用SMART Launcher启动我的应用(https://launch.smarthealthit.org/?tab=1&launch=WzAsIiIsIiIsIkFVVE8iLDAsMCwwLCIiLCIiLCIiLCIiLCIiLCIiLCIiLDEsMV0&validation=1)并在这里传递一些客户端ID和客户端密钥。然后,我试图在代码中使用这些值来检索授权码和令牌。
我正在使用Python的OAuth2.0库,其中我使用WebApplicationClient来获取授权URL。
https://URL/?error=invalid_request&error_description=Invalid+launch+options%3A+SyntaxError%3A+Unexpected+end+of+JSON+input
为什么会这样?我在这里做错了什么吗?下面是我写的代码。另外,我不知道如何在我的代码中以编程方式获取authorization_response(假设第一个问题已经解决)。

注意redirect_uri是我在ngrok上托管的应用的URL,是一个纯前端应用。

client = WebApplicationClient(client_id)   
authorize_endpoint = "https://launch.smarthealthit.org/v/r4/auth/authorize"    
redirect_uri = "https://URL"

authorization_url = client.prepare_request_uri(
  authorize_endpoint,
  redirect_uri = redirect_uri
)
print('Authorization URL: ', authorization_url)

parsed_response = client.parse_request_uri_response(authorization_response)
authorization_code = parsed_response["code"]

字符串
上面是导致错误的代码部分。我在这一步卡住了。我提供了我写的其余代码(下面)作为参考和上下文。它假设授权代码已经成功获得,并尝试获取访问令牌。

data = client.prepare_request_body(
  code = authorization_code,
  redirect_uri = redirect_uri,
  client_id = client_id,
  client_secret = client_secret
)
print('Token data: ', data)
token_response = requests.post(token_endpoint, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"})

if token_response.status_code == 200:
    access_token = token_response.json()["access_token"]
    print("Access Token:", access_token)
else:
    print("Error obtaining access token:", token_response.text)

bnl4lu3b

bnl4lu3b1#

根据评论,听起来你想让这是一个从EHR启动的SMART on FHIR应用程序。在这种情况下,你的授权URL的构建似乎不完整。你有authorization_url = client.prepare_request_uri(authorize_endpoint, redirect_uri = redirect_uri)。这将导致https://launch.smarthealthit.org/v/r4/auth/authorize?client_id=<client_id>&response_type=code&redirect_uri=https%3A%2F%2FURL的授权调用。
这个电话不见了...

  1. launch参数,设置为EHR提供的启动代码。
  2. scope参数,它定义了所需的作用域。通常它被设置为launch openid fhirUser,但只有你知道需要什么(在这个场景中需要“launch”)。
  3. aud参数,定义您计划调用的FHIR服务器。这是由EHR在iss参数中提供的。
  4. state参数,这是任意的,但出于安全原因使用。
    SMART IG的解释可能对您有帮助。上述信息假设您使用的服务器支持SMART实施指南的最新版本。您的服务器可能不需要某些参数。

相关问题