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

Ame*_*ner 11 python authentication flask flask-security http-token-authentication

我正在尝试允许用户使用来自单独Web服务的帐户登录我的Flask应用程序.我可以联系此Web服务的api并获得安全令牌.如何使用此令牌对用户进行身份验证,以便他们可以访问受限制的视图?

我不需要将用户保存到我自己的数据库中.我只想为会话验证它们.我相信这可以使用Flask-Security和@auth_token_required装饰器完成,但文档不是很详细,我不知道如何实现它.

编辑:

这是一个代码示例:

@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')
Run Code Online (Sandbox Code Playgroud)

F B*_*aut 19

嘿有Amedrikaner!

看起来您的用例非常简单,我们可以自己实现.在下面的代码中,我将把你的令牌存储在用户会话中并检入一个新的包装器.让我们开始创建自己的包装器,我通常只将它们放在一个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
Run Code Online (Sandbox Code Playgroud)

凉!

现在我们已经实现了包装器,我们可以将它们的令牌保存到会话中.超级简单.让我们修改你的功能......

@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)
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用@require_api_token包装器检查受保护的视图,如下所示...

@main.route('/super_secret')
@require_api_token
def super_secret():
    return "Sssshhh, this is a secret"
Run Code Online (Sandbox Code Playgroud)

编辑 哇!我忘了提到你需要在你的应用程序配置中设置你的SECRET_KEY.

只有一个带有SECRET_KEY ="SOME_RANDOM_STRING"的config.py文件就可以了.然后用...加载它

main.config.from_object(config)
Run Code Online (Sandbox Code Playgroud)