简体   繁体   English

如何在Flask中实现令牌认证?

[英]How do you implement token authentication in Flask?

I'm trying to allow users to login to my Flask app using their accounts from a separate web service. 我正在尝试允许用户使用来自单独Web服务的帐户登录我的Flask应用程序。 I can contact the api of this web service and receive a security token. 我可以联系此Web服务的api并获得安全令牌。 How do I use this token to authenticate users so that they have access to restricted views? 如何使用此令牌对用户进行身份验证,以便他们可以访问受限制的视图?

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')

Hey there Amedrikaner! 嘿有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"

EDIT Woah! 编辑哇! 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. 只有一个带有SECRET_KEY =“SOME_RANDOM_STRING”的config.py文件就可以了。 Then load it with... 然后用...加载它

main.config.from_object(config)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM