Search code examples
pythonflaskflask-restfulflask-restplus

How to send authentication credentials in app.post for Flask unit testing of API views


I have written a Flask application. In that, I am using basic auth to restrict certain POST API views. From Python requests, I can access those views as -

print post(url, json=data, auth=('username', 'password'))

And from curl,

curl -a username:password -d "data" url

How to do the same in app.post ? I tried auth, authorization etc as parameters to post but they were invalid.

response = self.app.post(
            url,
            data=data,
            headers={
            'content-type': 'application/json'
            },
            follow_redirects=True
        )

Solution

  • Basic authorization credentials are stored in header as follows -

    "Authorization": "Basic username:password"
    

    However the username:password part is base64 encoded. So one can use the base64 module to do the same.

    import base64
    
    headers={
       'content-type': 'application/json',
       'Authorization': 'Basic %s' % base64.b64encode('username:password')
    }
    

    In the above case, the Authorization will be set to Basic dXNlcm5hbWU6cGFzc3dvcmQ=

    This will allow you to use basic authorization from Flask testing framework. Cheers !!