Search code examples
pythonflaskbasic-authentication

Flask HTTPBasicAuth none token inside header


I'm trying to resolve problem with Basic Authentication in flask using HTTPBasicAuth.

When I'm accessing using curl or web browser everything works well. This are examples which works:

curl -u [access_token]:unused -i X GET http://127.0.0.1:5000/api/v1/token

or

http://[access_token]:[email protected]:5000/api/v1/token

But when I'm using Authorization: Basic [token] or Authorization: Basic [token]:unused in header of request I get 500 error from server.

Verifying access token or email and password:

@auth.verify_password
def verify_password(email_or_token, password):

   user = User.verify_auth_token(email_or_token)
   if not user:

      user = User.query.filter_by(email = email_or_token).first()
      if not user or not user.verify_password(password):
         return False
   g.user = user
   return True

User model:

class User(db.Model):

    def generate_auth_token(self, expiration = 600):
        s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
        return s.dumps({ 'id': self.id })

    @staticmethod
    def verify_auth_token(token):
       s = Serializer(app.config['SECRET_KEY'])
       try:
          data = s.loads(token)
       except SignatureExpired:
          return None # valid token, but expired
       except BadSignature:
          return None # invalid token
       user = User.query.get(data['id'])
       return user

I found that when I'm using token or email and password in header as Basic [token/email]:[password/unused], email_or_token and password properties are None.

Error: TypeError: argument of type 'NoneType' is not iterable

enter image description here

Why error occurs while using Authorization: Basic [token/email]:[password/unused] in header of request? What is solution for this?


Solution

  • You must Base64-encode the the credential portion of your Authorization header. This can be done with the command line base64 utility.

    echo 'token:unused' | base64
    

    From the example here, the username password combination of Aladdin:OpenSesame becomes:

    Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
    

    The reason that you don't have to worry about this with curl or the browser, is that they will perform the encoding automatically for you.