1

I am implementing basic authentication to validate username and password with the following code:

def auth_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        cur = get_db().cursor().execute("SELECT * FROM users where user_name='parag'")
        result = cur.fetchall()
        if auth and auth.username == result[0][user_name] and auth.password== result[0][password]:
            return True
        return make_response('could not verify', 401, {'WWW-authenticate' : 'Basic realm ="Login Required"'})
    return decorated

@app.route("/")
@auth_required
def index():
    data = request.get_json()
    cur = get_db().cursor())
    return '''<h1> hi paarg </h1>'''

but auth.username and auth.password is none. auth = request.authorization is coming as a NoneType. Please help.

  • Just wondering, is there a reason you are using @basic_auth.required while the decorator function is called auth_required – gittert Mar 12 at 9:54
  • @gittert thanks for pointing out the mistake. I have edited the code. Now you can see it what is wrong in it. – Parag Bhingre Mar 12 at 16:53
  • There is a flask snippet that does a similar thing (or you can use something like flask-login which has built in decorators for this purpose). See flask.pocoo.org/snippets/8. I cannot test your code but I think there is somethign going wrong in your database query. you should check the output of that query first to debug the issue. – gittert Mar 13 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.