2
votes

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'
1
Maybe you should use JWT (json web token) to keep being logged in.mama
@mama iirc flask_login doesn't require any kind of JWT while authentication. Isn't it?chsupark.03
No, sorry. I don't know how flask_login works. But i think everything you need to know is here flask-login.readthedocs.io/en/latest/#how-it-worksmama
See stackoverflow.com/questions/6878418/… for an example of how to use a cookie jar with requests. You'll need that, or something like it, so that cookies from a response will be sent with subsequent requests.Dave W. Smith
@DaveW.Smith That was the issue. Thanks for the help!chsupark.03

1 Answers

1
votes

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)