2

I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.

I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman: enter image description here

my JWT token authentication script is here:

 // Uses http.get() to load data from a single API endpoint
  list() {
    return this.http.get('api/', this.getHttpOptions());
  }

// helper function to build the HTTP headers
  getHttpOptions() {
    return {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'JWT ' + this._userService.token
      })
    };
  }

I tried using http.get() here. Thanks in advance!

the error will be like:

401 (Unauthorized)
hsbzzhz
  • 79
  • 10
  • are you seeing the header in the network request to api/ ? – karthick Nov 20 '18 at 23:42
  • I am having the same issue using Django rest framework Token and Ionic3. The headers appear to be set in the request, **Access-Control-Request-Headers authorization,content-type**. When i manually resend the request in firefox with the header as, **Authorization: Token xxxmyaccesstokenxxx** it succeeds which leads me to believe that Ionic/Angular is not setting the token in a way Django can access it. – SemajDraw Nov 23 '18 at 20:49
  • Hi @J.ward thanks for your reminds, I have followed https://stackoverflow.com/questions/35760943/how-can-i-enable-cors-on-django-rest-framework this tutorial to set my backend, for the front end, I set the Access-Control-Request-Headers, but it still doesn't work. I don't know which part went wrong, if the API can be accessed by Postman, does that means my API is correct? – hsbzzhz Nov 25 '18 at 23:00
  • Hi @hsbzzhz, i just figured out what was wrong today. Django loads its middlewares sequentially and CORS middleware must be near the top for it to be applied correctly throughout the app. I spent far too long figuring that out. I had already set CORS_ORIGIN_ALLOW_ALL = True in my app so it wasnt that for me but if some poor soul ever reads hopefully it saves them a few days of hair pulling. – SemajDraw Nov 27 '18 at 04:34

3 Answers3

1

Try this:

list() {
return this.http.get('api/', { this.getHttpOptions() });  
}

getHttpOptions() {
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'JWT ' + this._userService.token
  }); 
   return headers;
}
brando
  • 8,215
  • 8
  • 40
  • 59
  • Thank you, I tried in this way: return this.http.get(api/', {headers : this.getHttpOptions() });, but still doesn't work, same error code 401. I doubt the page hasn't refresh after I log in successful – hsbzzhz Nov 21 '18 at 03:58
  • Sorry that didn't work. That's almost exactly the code I use and it work fine for me. Strange – brando Nov 21 '18 at 04:54
0

Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.

this.http.get('api/', { headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'JWT ' + this._userService.token,
    'Authenticationtoken': 'JWT ' + this._userService.token
}) });
Nick Wang
  • 624
  • 3
  • 6
0

Thanks guys, I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend. https://www.youtube.com/watch?v=OIbndrrUYiY

hsbzzhz
  • 79
  • 10