diff --git a/sanic/request.py b/sanic/request.py index 62d89781..fd52ba90 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -8,8 +8,9 @@ from sanic.exceptions import InvalidUsage from .log import log - DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream" + + # HTTP/1.1: https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1 # > If the media type remains unknown, the recipient SHOULD treat it # > as type "application/octet-stream" @@ -72,6 +73,17 @@ class Request(dict): return self.parsed_json + @property + def token(self): + """ + Attempts to return the auth header token. + :return: token related to request + """ + auth_header = self.headers.get('Authorization', None) + if auth_header is not None: + return auth_header.split()[1] + return auth_header + @property def form(self): if self.parsed_form is None: diff --git a/tests/test_requests.py b/tests/test_requests.py index 5895e3d5..4e1fd1a5 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -112,6 +112,29 @@ def test_post_json(): assert response.text == 'OK' +def test_post_token(): + app = Sanic('test_post_token') + + @app.route('/') + async def handler(request): + return text('OK') + + payload = {'test': 'OK'} + + # uuid4 generated token. + token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf' + + headers = { + 'content-type': 'application/json', + 'Authorization': 'Token {}'.format(token) + } + + request, response = sanic_endpoint_test(app, data=json_dumps(payload), headers=headers) + + assert request.token == token + assert response.text == 'OK' + + def test_post_form_urlencoded(): app = Sanic('test_post_form_urlencoded')