简体   繁体   English

flask_login 总是返回 401 未授权

[英]flask_login always returning 401 unauthorized

I'm having issues with flask_login.我在使用 flask_login 时遇到问题。 But while testing I realized that I was getting 401 unauthorized error when I request a login_required route.但是在测试时,我意识到当我请求 login_required 路由时,我收到了 401 未经授权的错误。 I made sure I logged in.我确定我登录了。

Any help appreciated.任何帮助表示赞赏。 thanks!谢谢!

Here is my login function:这是我的登录 function:

@app.route('/login', methods=['POST'])
def login():
    req = request.values
    _id = req['id']
    _password = req['password']

    if _id not in USERS:
        return {'message': 'Invalid credentials'}, 401
    elif not USERS[_id].can_login(_password):
        return {'message': 'Invalid credentials'}, 401
    else:
        USERS[_id].authenticated = True
        login_user(USERS[_id], remember=True)
        return {'message': 'Logged in'}, 200

And here's my user model, if needed如果需要,这是我的用户 model

class User:
    def __init__(self, _id, _password, _score=0,
                 authenticated=False):
        self._id = _id
        self._password = _password
        self._score = _score
        self.authenticated = authenticated

    def __repr__(self):
        r = {
            'id': self._id,
            'password': self._password,
            'score': self._score,
        }
        return str(r)

    def can_login(self, _password):
        return self._password == _password

    def is_active(self):
        return True

    def get_id(self):
        return self._id

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        return False

This is my user_loader function这是我的 user_loader function

@login_manager.user_loader
def user_loader(_id):
    return USERS[_id]

And I tested it via requests module我通过请求模块对其进行了测试

>>> print(requests.post(url+"login", data={"id":"test", "password":"1"}).content)
b'{\n  "message": "Logged in"\n}\n'

>>> print(requests.get(url+"users").content)
b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>401 Unauthorized</title>\n<h1>Unauthorized</h1>\n<p>The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn\'t understand how to supply the credentials required.</p>\n'

My issue was that I wasn't storing a cookie in request.我的问题是我没有在请求中存储 cookie。 By making request.Session, I was able to make it work.通过提出 request.Session,我能够让它工作。

s = request.Session()
>>> print(s.post(url+"login", data={"id":"test", "password":"1"}).content)
>>> print(requests.get(url+"users").content)

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

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