I'm having issues with flask_login. But while testing I realized that I was getting 401 unauthorized error when I request a login_required route. I made sure I logged in.
Any help appreciated. thanks!
Here is my login 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
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
@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. By making request.Session, I was able to make it work.
s = request.Session()
>>> print(s.post(url+"login", data={"id":"test", "password":"1"}).content)
>>> print(requests.get(url+"users").content)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.