JWT token with jQuery Ajax

I have an API managed with Laurvel, Dingo and JWT Tokens. Testing an API call using PAW works great. Making API calls using jQuery without middleware. Disabling JWT Tokens works great. But as soon as I try to start an Ajax request with JWT tokens, I get 401.

I miss the trick with the Ajax request. Do 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 need to use jsonp due to Cross Domain. But then again, this works great with JWT middleware.

I hope you can advise ..

+5
source share
2 answers

I removed the API from the subdomain and its functionality. It should have something to do with jsonp and JWT tokens.

+1
source

The status code 401 HTTP is intended for โ€œUnauthorized accessโ€, that is, authentication is required and failed or has not yet been properly provided. In this case, this is because it was not properly provided. You are trying to provide it in the beforeSend parameter. beforeSend offers you the ability to manipulate XMLHttpRequest before sending it, but the problem is that you are using JSONP. And JSONP, since JSONP is a trick for entering the <script> , it does not use XMLHttpRequest , so manipulating it is pointless.

Here is a good explanation of exactly what JSONP is.

Your question: โ€œDo you see a problem with this code?โ€, To which I answered above. You probably want to ask: "How do I solve the authorization problem with jQuery?". You say, โ€œI need to use jsonp because of the cross domain,โ€ and if you talk a little more about โ€œbecause of the cross domain,โ€ the answer that will lead to the solution will be easier to produce. The answer in this release may solve your problems, but it's hard to say without additional information.

+1
source

Source: https://habr.com/ru/post/1237200/


All Articles