Skip to content

Instantly share code, notes, and snippets.

@joergeschmann
Created March 28, 2014 09:49
Show Gist options
  • Select an option

  • Save joergeschmann/9829096 to your computer and use it in GitHub Desktop.

Select an option

Save joergeschmann/9829096 to your computer and use it in GitHub Desktop.
Set Authorization header for every jQuery request
/* Check for local storage support */
if(typeof(localStorage) == "undefined") {
alert("no storage!");
}
/* var to encapsulate the logic */
var authController = authController || {};
authController.setAuthHeader = function(value) {
localStorage.setItem("authHeader", value);
};
authController.getAuthHeader = function() {
return "Basic " + (authController.isUserAvailable() ? localStorage.getItem("authHeader") : '');
};
authController.isUserAvailable = function() {
var authValue = localStorage.getItem("authHeader");
return authValue !== null && authValue !== '';
};
/* set header for every jQuery request */
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
jqXHR.setRequestHeader("Authorization", authController.getAuthHeader());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment