Search code examples
flaskwerkzeug

Flask werkzeug request.authorization is none but Authorization headers present


I am POSTing some JSON data and adding an Authorization header. However, the request object does not have the correct authorization property. HTTP_AUTHORIZATION and headers both show the proper authorization details.

{'authorization': None,
 'cookies': {},
 'environ': {'CONTENT_LENGTH': '81',
             'CONTENT_TYPE': u'application/json',
             'HTTP_AUTHORIZATION': 'testkey:',
             'HTTP_CONTENT_LENGTH': '81',
             'HTTP_CONTENT_TYPE': 'application/json',
             'HTTP_HOST': 'test',
             'PATH_INFO': '/v1/test',
             'QUERY_STRING': '',
             'REQUEST_METHOD': 'POST',
             'SCRIPT_NAME': '',
             'SERVER_NAME': 'test',
             'SERVER_PORT': '80',
             'SERVER_PROTOCOL': 'HTTP/1.1',
             'flask._preserve_context': False,
             'werkzeug.request': <Request 'http://test/v1/test' [POST]>,
             'wsgi.errors': <open file '<stderr>', mode 'w' at 0x10d5471e0>,
             'wsgi.input': <_io.BytesIO object at 0x11074c410>,
             'wsgi.multiprocess': False,
             'wsgi.multithread': False,
             'wsgi.run_once': False,
             'wsgi.url_scheme': 'http',
             'wsgi.version': (1, 0)},
 'headers': EnvironHeaders([('Authorization', testkey:'), ('Host', u'test'), ('Content-Length', u'81'), ('Content-Type', u'application/json')]),
 'shallow': False,
 'url': u'http://test/v1/test',
 'url_rule': <Rule '/v1/test' (POST, OPTIONS) -> testresource>,
 'view_args': {}}

Solution

  • Your authorization header ('Authorization', 'testkey:') needs to be Base64 encoded and include Basic.

    in python:

    import base64
    base64.b64encode('testkey:') # 'dGVzdGtleTo='
    

    in javascript set your header using btoa:

    '{"Authorization": "Basic ' + btoa('testkey:') + '"}' 
    '{"Authorization": "Basic dGVzdGtleTo="}' 
    

    In your case, the this will result in the header coming in as:

    ('Authorization', 'Basic dGVzdGtleTo=')