How to pass JsonWebToken(JWT) through AngularJS












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)









share|improve this question

























  • 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.

    – J.ward
    Nov 23 '18 at 20:49











  • Hi @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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.

    – J.ward
    Nov 27 '18 at 4:34
















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)









share|improve this question

























  • 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.

    – J.ward
    Nov 23 '18 at 20:49











  • Hi @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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.

    – J.ward
    Nov 27 '18 at 4:34














2












2








2


1






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)









share|improve this question
















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)






angularjs django-rest-framework jwt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 3:50







hsbzzhz

















asked Nov 20 '18 at 23:32









hsbzzhzhsbzzhz

367




367













  • 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.

    – J.ward
    Nov 23 '18 at 20:49











  • Hi @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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.

    – J.ward
    Nov 27 '18 at 4:34



















  • 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.

    – J.ward
    Nov 23 '18 at 20:49











  • Hi @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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.

    – J.ward
    Nov 27 '18 at 4:34

















are you seeing the header in the network request to api/ ?

– karthick
Nov 20 '18 at 23:42





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.

– J.ward
Nov 23 '18 at 20:49





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.

– J.ward
Nov 23 '18 at 20:49













Hi @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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 @J.ward thanks for your reminds, I have followed stackoverflow.com/questions/35760943/… 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.

– J.ward
Nov 27 '18 at 4:34





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.

– J.ward
Nov 27 '18 at 4:34












3 Answers
3






active

oldest

votes


















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;
}





share|improve this answer


























  • 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 3: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 4: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
}) });





share|improve this answer































    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






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403192%2fhow-to-pass-jsonwebtokenjwt-through-angularjs%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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;
      }





      share|improve this answer


























      • 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 3: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 4:54
















      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;
      }





      share|improve this answer


























      • 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 3: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 4:54














      1












      1








      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;
      }





      share|improve this answer















      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;
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 21 '18 at 0:44

























      answered Nov 21 '18 at 0:23









      brandobrando

      5,51852951




      5,51852951













      • 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 3: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 4:54



















      • 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 3: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 4:54

















      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 3:58





      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 3: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 4:54





      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 4: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
      }) });





      share|improve this answer




























        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
        }) });





        share|improve this answer


























          0












          0








          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
          }) });





          share|improve this answer













          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
          }) });






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 4:40









          Nick WangNick Wang

          54925




          54925























              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






              share|improve this answer




























                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






                share|improve this answer


























                  0












                  0








                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 26 '18 at 0:40









                  hsbzzhzhsbzzhz

                  367




                  367






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403192%2fhow-to-pass-jsonwebtokenjwt-through-angularjs%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Tangent Lines Diagram Along Smooth Curve

                      Yusuf al-Mu'taman ibn Hud

                      Zucchini