首页 > 解决方案 > Flask Spotify API 注销功能

问题描述

我有一个小型 Flask 应用程序,它允许 Spotify 用户在主页上进行身份验证。登录和访问令牌等工作正常,如下所示。我收到了一个 http 302 响应,它可以正确地/spotify_authentication重定向我。/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 自己的注销页面,以将我从他们的平台而不是我的应用程序中注销。

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

标签: pythonapiauthenticationflaskaccess-token

解决方案


对我来说,您似乎只需要清除包含访问令牌的会话变量


推荐阅读