我正在开发一个 Flask 应用程序,允许用户使用 OAuth(以 Github 作为提供者)和 Flask-dance 库登录。由于某种原因,成功登录后,我无法重定向到我将用户发送到登录页面的页面。
当用户尝试连接时,例如http://localhost:6675/examples/tutorial.first/ http://localhost:6675/examples/tutorial.first/,用户被重定向到登录页面,在 URL 中显示我们应该重定向到的页面(http://localhost:6675/login?next=%2Fexamples%2Ftutorial.first%2F http://localhost:6675/login?next=%2Fexamples%2Ftutorial.first%2F)
问题是,当我成功使用 Github 登录后,应用程序只是返回到主页。
我在检查 Flask-dance文档 https://flask-dance.readthedocs.io/en/latest/以及文档make_github_blueprint()
函数提到参数redirect_to
and redirect_url
,但是当我尝试使用它们时,我什至无法完成登录步骤。此外,它似乎只适用于静态地址,而理想情况下我想跳回到登录之前的页面。我还检查了这个问题 https://stackoverflow.com/questions/49749572/google-oauth-with-flask-dance-always-redirect-to-choose-account-google-page,但问题似乎有所不同。
有没有关于如何在使用 Flask dance 登录后正确进行重定向的示例?
这里有一些可能相关的代码片段。
在里面init.py 文件:
bp_github = make_github_blueprint(
client_id="...",
client_secret="...",
)
login_manager = LoginManager()
login_manager.login_github_view = 'github.login'
login_manager.login_view = 'login'
在 app.py 文件中:
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return flask.redirect(flask.url_for('/'))
return flask.render_template('login.html')
@app.route("/logout")
@login_required
def logout():
logout_user()
flask.flash("You have logged out")
return flask.redirect(flask.url_for("login"))
@oauth_authorized.connect_via(bp_github)
def logged_in(blueprint, token):
"""
create/login local user on successful OAuth login with github
:param blueprint:
:param token:
:return:
"""
if not token:
flask.flash("Failed to log in.", category="error")
return False
session = blueprint.session
resp = session.get("/user")
if not resp.ok:
msg = "Failed to fetch user info."
flask.flash(msg, category="error")
return False
user_id = str(info["id"])
# Find this OAuth token in the database, or create it
query = OAuth.query.filter_by(
provider=blueprint.name,
provider_user_id=user_id,
)
try:
oauth = query.one()
except NoResultFound:
oauth = OAuth(
provider=blueprint.name,
provider_user_id=user_id,
token=token,
)
if oauth.user:
login_user(oauth.user)
flask.flash("Successfully signed in.")
else:
# Create a new local user account for this user
name = info['login']
user = User(
email=info["email"],
name=name,
provider=provider
)
# Associate the new local user account with the OAuth token
oauth.user = user
# Save and commit our database models
db.session.add_all([user, oauth])
db.session.commit()
# Log in the new local user account
login_user(user)
flask.flash("Successfully signed in.")
# Disable Flask-Dance's default behavior for saving the OAuth token
return False