如何获得干净的网址?

时间:2017-07-29 17:06:26

标签: flask oauth2client

from flask import Flask, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth


app = Flask(__name__)
app.config['GOOGLE_ID'] = "12"
app.config['GOOGLE_SECRET'] = "A"BC
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

google = oauth.remote_app(
    'google',
    consumer_key=app.config.get('GOOGLE_ID'),
    consumer_secret=app.config.get('GOOGLE_SECRET'),
    request_token_params={
        'scope': 'email'
    },
    base_url='https://www.googleapis.com/oauth2/v1/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
)

@app.route('/')
def index():
    if 'google_token' in session:
        me = google.get('userinfo')
        return jsonify({"data": me.data})
    return redirect(url_for('login'))


@app.route('/login')
def login():
    return google.authorize(callback=url_for('authorized', _external=True))


@app.route('/logout')
def logout():
    session.pop('google_token', None)
    return redirect(url_for('index'))


@app.route('/login/authorized')
def authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    return jsonify({"data": me.data})


@google.tokengetter
def get_google_oauth_token():
    return session.get('google_token')

当我通过谷歌登录时,我的网址会更改为:

  

http://localhost:5000/login/authorized?code=4/U89v8kn76_zspiZUuZwdv01KuifACegxtt7NWBQLF3w#

我想要的是我在网址中提供的内容

  

http://localhost:5000/login/authorized

我该怎么办?

1 个答案:

答案 0 :(得分:1)

这听起来像是auth进程的回调部分的预期行为。

您要做的是将用户重定向到authorized()功能末尾的主路线。该功能或多或少“属于”OAuth流程(是一种思考它的好方法)。您只需确定该过程是否成功,然后将用户重定向到他们需要去的地方。

我喜欢在此过程中使用Message Flashing与用户进行通信。

例如:

@app.route('/')
def index():
    if 'google_token' not in session:
        flash("Please log in to see this page")
        return redirect(url_for('login'))
    me = google.get('userinfo')
    return render_template("index.html", user=me)

@app.route('/login/authorized')
def authorized():
    resp = google.authorized_response()
    if resp is None:
        flash("Access denied: reason={0} error={1}".format(
            request.args['error_reason'],
            request.args['error_description']
        ))
        return redirect(url_for("login"))
    session['google_token'] = (resp['access_token'], '')
    flash("Successful login!")  # superfluous, just for example
    return redirect(url_for("index"))

你应该在这里看到会话密钥存在(例如cyrptocookie)...显然你应该按照文档<{1}}设置密钥