JQuery AJAX Authorization

I am trying to authorize an AJAX request based on this guide . It sets request headers before sending with the corresponding authorization information using the Crypto library. The problem I am facing is that the headers do not seem to be set on demand. Here is my code:

beforeSend : function(xhr) { var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password); var base64 = Crypto.util.bytesToBase64(bytes); xhr.setRequestHeader("Authorization", "Basic " + base64); }, 
+6
source share
2 answers

The problem was not setting dataType to JSONP . Since this was not done, the browser interpreted the call as a standard AJAX request, which meant that it was blocked in the policy with the same source.

Working code for reference (credit refers to @pdeschen for Crpyto offer):

 <script type='text/javascript'> // define vars var username = ''; var password = ''; var url = ''; // ajax call $.ajax({ url: url, dataType : 'jsonp', beforeSend : function(xhr) { // generate base 64 string from username + password var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password); var base64 = Crypto.util.bytesToBase64(bytes); // set header xhr.setRequestHeader("Authorization", "Basic " + base64); }, error : function() { // error handler }, success: function(data) { // success handler } }); </script> 
+8
source

It finally works for me. There may be collisions based on an individual call. Sets this method by default for future connection settings.

 //Function( jqXHR jqXHR ) $.ajaxSetup( {beforeSend: function(jqXHR) { jqXHR.setRequestHeader( "My-Header", "My-Value" ); } } ); 
0
source

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


All Articles