简体   繁体   English

flask-HTTPTokenAuth 验证令牌失败

[英]flask-HTTPTokenAuth Fails to Verify Token

I'm working my way through Miguel Grinberg's book Flask Web Development, and I've run into a snag in Chapter 14 (Application Programming Interfaces) with the authentication routine.我正在阅读 Miguel Grinberg 的书 Flask Web Development,我在第 14 章(应用程序编程接口)中遇到了身份验证例程的障碍。 I'm attempting to update the code to use the current version of flask-HTTPAuth according to the example code in the github repo.我正在尝试根据 github 存储库中的示例代码更新代码以使用当前版本的 flask-HTTPAuth。 I can authenticate to HTTPBasicAuth with email/password, but when I try to pass a token I still get a password prompt.我可以使用电子邮件/密码向 HTTPBasicAuth 进行身份验证,但是当我尝试传递令牌时,我仍然会收到密码提示。

Here is my app/api/authentication.py file:这是我的 app/api/authentication.py 文件:

from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

from ..models import User
from . import api
from .errors import forbidden, unauthorized


basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Bearer')
multi_auth = MultiAuth(basic_auth, token_auth)


@basic_auth.verify_password
def verify_password(email, password):
    if email == '':
        return False
    user = User.query.filter_by(email=email).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    if user.verify_password(password):
        return user
    else:
        return False

@token_auth.verify_token
def verify_token(token):
    user = User.verify_auth_token(token)
    if user:
        g.current_user = user
        g.token_used = True
        return user
    else:
        return False

@basic_auth.error_handler
def auth_error():
    return unauthorized('Invalid credentials')

@token_auth.error_handler
def auth_error():
    return unauthorized('Invalid credentials')

@api.before_request
@multi_auth.login_required
def before_request():
    if not g.current_user.is_anonymous and not g.current_user.confirmed:
        return forbidden('Unconfirmed account')

@api.route('/tokens/', methods=['POST'])
@multi_auth.login_required
def get_token():
    if g.current_user.is_anonymous or g.token_used:
        return unauthorized('Invalid credentials')
    return jsonify({'token': g.current_user.generate_auth_token(), 'expiration': 3600})

I'm using Python 3.10.6, Flask 2.2.2 and HTTPie 3.2.1.我正在使用 Python 3.10.6、Flask 2.2.2 和 HTTPie 3.2.1。 What am I doing wrong?我究竟做错了什么?

I've figured it out.我想通了。 The current version of HTTPie (3.2.1) needs to know whether you're sending a token or a userid:password pair.当前版本的 HTTPie (3.2.1) 需要知道您发送的是令牌还是用户 ID:密码对。 To do this, you use the command为此,您可以使用命令

http --auth <username>:<password> ...

for basic authentication or用于基本身份验证或

http --auth-type bearer --auth <token> ...

for token authentication.用于令牌认证。

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

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