python - python:如何从桌面应用程序重定向到url,等待用户接受授权并获取授权码
问题描述
我正在使用 Spotify API 开发一个应用程序,但我对这一切有点陌生。我正在尝试使用用于代码交换的证明密钥 (PKCE) 获取授权代码(https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof- key-for-code-exchange-pkce)我的问题是如何将用户重定向到query
他必须接受授权的地方,并使我的应用程序等到用户点击接受。当他这样做时,用户将被重定向,并且该新 URL(如文档所述)将包含我需要的授权代码,然后将其交换为授权令牌。
到目前为止,这是我获取该授权码的功能:
def get_auth_code(self):
code_challenge = self.get_code_challenge_PKCE()
scopes_needed = "user-read-email%20user-read-private%20playlist-read-collaborative%20playlist-modify-public%20playlist-read-private%20playlist-modify-private%20user-library-modify%20user-library-read"
endpoint = "https://accounts.spotify.com/authorize"
query = f"{endpoint}?client_id={self.client_ID}&response_type=code&redirect_uri={self.redirect_uri}&scope={scopes_needed}&code_challenge_method=S256&code_challenge={code_challenge}"
webbrowser.open(query)
解决方案
设置一个网络服务器。
要以编程方式提取访问令牌,您需要一个 Web 服务器来在用户登录 Spotify(您将他们重定向到)后处理重定向。现在这个服务器可以是用户将 URI 粘贴到终端上的输入字段,但显然这对于用户体验来说并不理想。它为许多错误留下了空间。
我编写了一个 Spotify Web API 客户端,它的内部结构可能对您有用。例如,您可以使用 Flask 来构建服务器。主要原则是使用一个端点(即/login
)将用户重定向(307
为我工作的代码浏览器不会记住它)到一个回调(即/callback
),它接收code
您可以请求访问令牌的参数。
我知道,在本地实施 OAuth2 可能有点麻烦。在我的库中,我还制作了一个类似的函数,你正在使用 构建webbrowser
,但它确实有手动复制粘贴的怪癖。要使用功能,您可以为简洁起见定义自己,其要点是:
verifier = secrets.token_urlsafe(32) # for PKCE, not in my library yet
url = user_authorisation_url(scope, state, verifier)
# Communicate with the user
print('Opening browser for Spotify login...')
webbrowser.open(url)
redirected = input('Please paste redirect URL: ').strip()
code = parse_code_from_url(redirected)
state_back = parse_state_from_url(redirected)
assert state == state_back # For that added security juice
token = request_user_token(code, verifier)
推荐阅读
- .net-core - 在 Visual Studio 2019(发布配置文件)中使用变量和相对路径时出现问题
- python - python groupby.apply中的值不匹配
- python - 搜索字典键、嵌套字典中匹配的值、包含在列表中
- javascript - 使用 JavaScript RegEx 验证输入
- java - 仅当密钥已存在时才更新数据库
- mongodb - 如果我使用 security.authorization: enabled 运行 mongod,如何进行身份验证?
- x86 - 松弛内存模型上的断点行为
- web - 使用 AFL++ Fuzz Web 应用程序并记录错误消息
- node.js - TypeError:无法读取未定义 discord.js 的属性“主题”
- pagination - 在具有“合并”功能的 apollo 客户端分页配置中,即使调用 fetchMore,现有缓存数据也始终为空