【问题标题】:Flask Spotify API Logging out functionFlask Spotify API 注销功能
【发布时间】:2020-04-14 06:04:30
【问题描述】:

我有一个小型 Flask 应用程序,它允许 Spotify 用户在主页上进行身份验证。登录和访问令牌等工作正常,如下所示。我收到了针对 /spotify_authentication 视点的 http 302 响应,它正确地将我重定向到 /spotify

#  Client Keys
CLIENT_ID = "##"
CLIENT_SECRET = "##"

# Spotify URLS
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_API_BASE_URL = "https://api.spotify.com"
API_VERSION = "v1"
SPOTIFY_API_URL = "{}/{}".format(SPOTIFY_API_BASE_URL, API_VERSION)

CLIENT_SIDE_URL = "http://127.0.0.1:5000/spotify"
REDIRECT_URI = "http://127.0.0.1:5000/spotify"

SCOPE = 'user-read-private user-read-playback-state user-modify-playback-state user-library-read'
STATE = ""
SHOW_DIALOG_bool = True
SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()

auth_query_parameters = {
    "response_type": "code",
    "redirect_uri": REDIRECT_URI,
    "scope": SCOPE,
    "client_id": CLIENT_ID
}


@app.route('/spotify_authentication')
def spotify_auth():
    url_args = "&".join(["{}={}".format(key,urllib.parse.quote(val)) for key, val in auth_query_parameters.items()])
    auth_url = "{}/?{}".format(SPOTIFY_AUTH_URL, url_args)

    return redirect(auth_url)

@app.route('/spotify')
def spotify():
    auth_token = request.args['code']
    code_payload = {
        "grant_type": "authorization_code",
        "code": str(auth_token),
        "redirect_uri": REDIRECT_URI
    }

    base64encoded = base64.b64encode("{}:{}".format(CLIENT_ID, CLIENT_SECRET).encode())
    headers = {"Authorization": "Basic {}".format(base64encoded.decode())}
    post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)

    response_data = json.loads(post_request.text)
    access_token = response_data["access_token"]
    refresh_token = response_data["refresh_token"]
    token_type = response_data["token_type"]
    expires_in = response_data["expires_in"]

    authorization_header = {"Authorization":"Bearer {}".format(access_token)}

    return render_template('spotify.html')

现在我想实现一个注销按钮来终止身份验证。网上似乎没有很多有用的答案。有些指导您将/logout 视图点重定向到另一个页面。当我这样做时,我可以在网络浏览器中返回到我的认证页面——这并不意味着退出我!例如,定向到accounts.spotify.com/logout 会将我重定向到 Spotify 自己的注销页面,以将我从他们的平台而不是我的应用程序中注销。

如何使用 Python 3 实现一种注销方法,该方法擦除身份验证访问权限并正确重定向到 /spotify_authentication?我不介意用户是否必须使用他们的凭据再次进行身份验证。

【问题讨论】:

    标签: python api authentication flask access-token


    【解决方案1】:

    在我看来,您只需清除包含访问令牌的会话变量

    【讨论】:

    • 所以我应该在新的注销视点上设置access_token = ' '
    • 我不太明白,但我相信你有使用 access_token 的前端代码,我假设你将它存储为前端会话变量,如果是这种情况你需要清除它来自浏览器。可以从烧瓶中执行此session.clear() 或使用 JavaScript 检查 SO answer
    • 我没有使用任何会话。如何从 auth 生成会话?
    • 您能否也发布您的前端代码spotify.html。这部分是发送数据到webbrowserdef spotify()最后一部分
    • spotify.html 目前为空!我还没有开始将任何数据解析到前端。但身份验证等出现在搜索栏中,带有令牌等。
    猜你喜欢
    • 2017-01-25
    • 2013-05-10
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 2023-03-31
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多