Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-login request_loader not working?

I'm trying to implement Basic Auth on my Flask application with the Flask-Login extension. Following the documentation i tried an example request loader, but it gives me a 401 Unauthorized error, while the soon to be depreciated header_loader works perfectly, so am i doing something wrong or is there a bug in the request_loader.

I use the following request_loader:

login_manager = LoginManager(app)

@login_manager.request_loader
def load_user_from_request(req):
    print req.headers   # just to see what happens
    user = models.Werknemer.query.first() #this user exists, so it always returns a user
    return user

My protected view:

@app.route("/test")
@login_required
def index():
    return 'OK'

And my request code:

import requests
from requests.auth import HTTPBasicAuth

test_req = requests.get('http://localhost:5000/test', auth=HTTPBasicAuth('test', 'test'))
print test_req.content

when I run my request code it returns:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>401 Unauthorized</title>
<h1>Unauthorized</h1>
<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>

when I leave out the auth part of my request it returns my protected view. Why is flask not accepting the Basic auth header ?

like image 627
Jeffrey Slort Avatar asked Mar 24 '14 22:03

Jeffrey Slort


1 Answers

I'm taking Pluralsight's course on this now and I got the same error. It worked after I corrected the syntax in the setup of the authentication.

# Configure authentication
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app)

I had typed the last line incorrectly and got the 404 error. Fixed the line and it worked.

like image 176
Carl James Avatar answered Nov 03 '22 05:11

Carl James