Python 你如何在 Flask 中实现令牌认证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32510290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you implement token authentication in Flask?
提问by Amerikaner
I'm trying to allow users to login to my Flask app using their accounts from a separate web service. I can contact the api of this web service and receive a security token. How do I use this token to authenticate users so that they have access to restricted views?
我正在尝试允许用户使用他们的帐户从单独的 Web 服务登录到我的 Flask 应用程序。我可以联系此 Web 服务的 api 并接收安全令牌。如何使用此令牌对用户进行身份验证,以便他们可以访问受限视图?
I don't need to save users into my own database. I only want to authenticate them for a session. I believe this can be done using Flask-Security and the @auth_token_required decorator but the documentation is not very detailed and I'm not sure how to implement this.
我不需要将用户保存到我自己的数据库中。我只想验证他们的会话。我相信这可以使用 Flask-Security 和 @auth_token_required 装饰器来完成,但文档不是很详细,我不确定如何实现。
EDIT:
编辑:
Here's a code example:
这是一个代码示例:
@main.route("/login", methods=["GET", "POST"])
def login():
payload = {"User": "john", "Password": "password123"}
url = "http://webserviceexample/api/login"
headers = {'content-type': 'application/json'})
#login to web service
r = requests.post(url, headers=headers, json=payload)
response = r.json()
if (r.status_code is 200):
token = response['user']['authentication_token']
# allow user into protected view
return render_template("login.html", form=form)
@main.route('/protected')
@auth_token_required
def protected():
return render_template('protected.html')
采纳答案by F Boucaut
Hey there Amedrikaner!
嘿,美国佬!
It looks like your use-case is simple enough that we can implement this ourselves. In the code below, I'll be storing your token in the users session and checking in a new wrapper. Let's get started by making our own wrapper, I usually just put these in a wrappers.py file but can you can place it where you like.
看起来您的用例很简单,我们可以自己实现。在下面的代码中,我会将您的令牌存储在用户会话中并签入一个新的包装器。让我们开始制作我们自己的包装器,我通常只是把它们放在一个 wrappers.py 文件中,但你可以把它放在你喜欢的地方。
def require_api_token(func):
@wraps(func)
def check_token(*args, **kwargs):
# Check to see if it's in their session
if 'api_session_token' not in session:
# If it isn't return our access denied message (you can also return a redirect or render_template)
return Response("Access denied")
# Otherwise just send them where they wanted to go
return func(*args, **kwargs)
return check_token
Cool!
凉爽的!
Now we've got our wrapper implemented we can just save their token to the session. Super simple. Let's modify your function...
现在我们已经实现了我们的包装器,我们可以将他们的令牌保存到会话中。超级简单。让我们修改您的功能...
@main.route("/login", methods=["GET", "POST"])
def login():
payload = {"User": "john", "Password": "password123"}
url = "http://webserviceexample/api/login"
headers = {'content-type': 'application/json'})
#login to web service
r = requests.post(url, headers=headers, json=payload)
response = r.json()
if (r.status_code is 200):
token = response['user']['authentication_token']
# Move the import to the top of your file!
from flask import session
# Put it in the session
session['api_session_token'] = token
# allow user into protected view
return render_template("login.html", form=form)
Now you can check the protected views using the @require_api_token wrapper, like this...
现在您可以使用@require_api_token 包装器检查受保护的视图,如下所示...
@main.route('/super_secret')
@require_api_token
def super_secret():
return "Sssshhh, this is a secret"
EDITWoah! I forgot to mention you need to set your SECRET_KEY in your apps config.
编辑哇!我忘了提到你需要在你的应用程序配置中设置你的 SECRET_KEY。
Just a config.py file with SECRET_KEY="SOME_RANDOM_STRING" will do. Then load it with...
只需一个带有 SECRET_KEY="SOME_RANDOM_STRING" 的 config.py 文件就可以了。然后加载它...
main.config.from_object(config)