用户ID与OAuth2不一致

bt1cpqcv  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(112)

我正在尝试在应用程序中设置Discord OAuth授权。
该脚本生成一个具有授权的URL,然后重定向到一个网页,该网页应从URL中提取access _token参数并将其发送回服务器。
请帮我设置获取和发送响应到我的其他服务器。

from flask import Flask, request

application = Flask(__name__)

@application.route('/redirect')
def redirect_handler():
    access_token = request.args.get('access_token')
    if access_token:
        return access_token
    else:
        return "Error."

if __name__ == "__main__":
   application.run(host='0.0.0.0')

我期望脚本能够从URL中提取“access_token”,但这并没有发生。URL看起来像这样;

https://tatarchik.cfd/login#token_type=Bearer&access_token=UXWVLCyTTL7tBDVRwzjcGA5qSC1zRs&expires_in=604800&scope=identify
5jvtdoz2

5jvtdoz21#

由于您没有提供太多的代码,我建议您使用Discord提供的代码示例。在callback函数上,用户授权应用程序后,您将获得他们的access_tokentoken['access_token']。确保更改OAUTH2_CLIENT_IDOAUTH2_CLIENT_SECRETOAUTH2_REDIRECT_URI变量。

import os
from flask import Flask, session, redirect, request
from requests_oauthlib import OAuth2Session
import requests

OAUTH2_CLIENT_ID = 888888888888
OAUTH2_CLIENT_SECRET = ""
OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback'

API_BASE_URL = os.environ.get('API_BASE_URL', 'https://discordapp.com/api')
AUTHORIZATION_BASE_URL = API_BASE_URL + '/oauth2/authorize'
TOKEN_URL = API_BASE_URL + '/oauth2/token'

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = OAUTH2_CLIENT_SECRET

if 'http://' in OAUTH2_REDIRECT_URI:
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

def token_updater(token):
    session['oauth2_token'] = token

def make_session(token=None, state=None, scope=None):
    return OAuth2Session(
        client_id=OAUTH2_CLIENT_ID,
        token=token,
        state=state,
        scope=scope,
        redirect_uri=OAUTH2_REDIRECT_URI,
        auto_refresh_kwargs={
            'client_id': OAUTH2_CLIENT_ID,
            'client_secret': OAUTH2_CLIENT_SECRET,
        },
        auto_refresh_url=TOKEN_URL,
        token_updater=token_updater)

@app.route('/')
def index():
    scope = request.args.get(
        'scope',
        'identify')
    discord = make_session(scope=scope.split(' '))
    authorization_url, state = discord.authorization_url(AUTHORIZATION_BASE_URL)
    session['oauth2_state'] = state
    return redirect(authorization_url)

@app.route('/callback')
def callback():
    if request.values.get('error'):
        return request.values['error']
    discord = make_session(state=session.get('oauth2_state'))
    token = discord.fetch_token(
        TOKEN_URL,
        client_secret=OAUTH2_CLIENT_SECRET,
        authorization_response=request.url)
    session['oauth2_token'] = token
    return token['access_token']

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=False, use_reloader=False)

相关问题