Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT token with jQuery Ajax

I have an API being driven with Laravel, Dingo and JWT Tokens. Testing the API call with PAW works perfectly. Running the API calls with jQuery without middleware JWT Tokens disable works fine. But as soon as I try running an Ajax request with JWT Tokens Im getting a 401.

Am I missing a trick with the Ajax Request. Can you see a problem with this code?

$.ajax({
    url: "http://api.domain.app/products",
    dataType : 'jsonp',
    type: 'GET',
    beforeSend : function(xhr) {
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("Authorization", "Bearer XXXX");
    },
    error : function() {
        // error handler
    },
    success: function(data) {
        console.log(data);
        return data;
    }
});

I am having to use jsonp due to Cross Domain. But again this is working fine turing off the JWT middleware.

Hope you can advise..

like image 394
Lee Avatar asked Oct 30 '22 14:10

Lee


2 Answers

I removed the API from the subdomain and its working fine. It must have something to do with jsonp and JWT Tokens.

like image 142
Lee Avatar answered Nov 08 '22 07:11

Lee


The HTTP status code 401 is for "Unauthorized", meaning authentication is required and has failed or has not yet been properly provided. In this case, it is because it has not been properly provided. You are trying to provide it in the beforeSend parameter. beforeSend offers you a chance to manipulate the XMLHttpRequest before it is sent, but the problem is, you are using JSONP. And JSONP since JSONP is just a <script> tag insertion trick, it does not use XMLHttpRequest, so manipulating it is pointless.

Here is a good explanation on exactly what JSONP is.

Your question was, "Can you see a problem with this code?", which I have answered above. What you probably want to ask though, is "How do I get the authorization issue to work with jQuery?". You say "I am having to use jsonp due to Cross Domain", and if you elaborate a bit more on the "due to Cross Domain", an answer leading to to a solution will be easier to produce. The answer in this issue might solve your problems, but it's difficult to tell without more information.

like image 29
StubbornShowaGuy Avatar answered Nov 08 '22 06:11

StubbornShowaGuy