1

I have my rest-api set up in Django and am using React Native to connect with it. I have registered users and am able to generate tokens however I am unable to pass the token in the header of the GET request. My code is as follows:

try{
        let response = await fetch("http://127.0.0.1:8000/fishes/auth/",
          {
          method: 'GET',
          headers: {
          //  'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': ' Token '+accessToken,
          }});

        let res = await response.text(); 
}}

I have been following this link http://cheng.logdown.com/posts/2015/10/27/how-to-use-django-rest-frameworks-token-based-authentication and have already verified that the response from the rest api is correct.

However on the phone with native react I get the following error in the console:

TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.js:441)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)

What am I doing wrong in the GET code?

blaziken105
  • 501
  • 3
  • 10
  • 25
  • What's the error code you are getting ? – Bipul Jain Feb 03 '17 at 15:47
  • I get a 401 error code from the server that being of an unauthorised user, it probably means that the token is not reaching the server in the correct format. I have also tried replacing the fetch url with "http://127.0.0.1:8000/fishes/auth/"+"'Authorization: Token" + accessToken+"''" What seems to be the problem here? – blaziken105 Feb 03 '17 at 15:52
  • Did the solution work ? – Bipul Jain Feb 04 '17 at 19:55

3 Answers3

0

Alright 401 status code which means UnAuthorized. For Django Rest Framework you must pass in the access Token as part of header for all your API requests.

Header Format will be

Key : Authorization
Value:  Token <token>

You can see more here http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
0

I think that you need change

'Content-Type' to 'content-type'

On lowercase

11400.es
  • 69
  • 1
  • 3
0

See This answer.

The same-origin policy restricts the kinds of requests that a Web page can send to resources from another origin.

In the no-cors mode, the browser is limited to sending “simple” requests — those with safelisted methods and safelisted headers only.

To send a cross-origin request with headers like Authorization and X-My-Custom-Header, you have to drop the no-cors mode and support preflight requests (OPTIONS).

The distinction between “simple” and “non-simple” requests is for historical reasons. Web pages could always perform some cross-origin requests through various means (such as creating and submitting a form), so when Web browsers introduced a principled means of sending cross-origin requests (cross-origin resource sharing, or CORS), it was decided that such “simple” requests could be exempt from the preflight OPTIONS check.

I got around this issue by handling preflight request, as stated by the OP.

Previously, in my middleware, I filtered out requests that did not include an auth token and return 403 if they were trying to access private data. Now, I check for preflight and send a response allowing these types of headers. This way, when the following request comes (get, post, etc), it will have the desired headers and I can use my middleware as originally intended.

Here is my middleware:

class ValidateInflight(MiddlewareMixin):

def process_view(self, request, view_func, view_args, view_kwargs):
    assert hasattr(request, 'user')
    path = request.path.lstrip('/')

    if path not in EXEMPT_URLS:
        logger.info(path)
        header_token = request.META.get('HTTP_AUTHORIZATION', None)
        if header_token is not None:
            try:
                token = header_token
                token_obj = Token.objects.get(token=token)
                request.user = token_obj.user
            except Token.DoesNotExist:
                return HttpResponse(status=403)
        elif request.method == 'OPTIONS':
            pass
        else:
            return HttpResponse(status=403)

Here is my Options handling

class BaseView(View):
 def options(self, request, *args, **kwargs):
     res = super().options(request, *args, **kwargs)
     res['Access-Control-Allow-Origin'] = '*'
     res['Access-Control-Allow-Headers'] = '*'
     return res
Stuart
  • 151
  • 7