Set ajax response status code to 401(unauthorized) when the user is not authorized

public @ResponseBody String handleRequest() {

if (null == currentUser) {

return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);

} else {

// do stuff…

return “blahblah…”;

}

}

In the ajax function, when detect unauthorized header then re-direct to log in page:

if (responseStatus == 401) {

window.location.href=”/login”;

}

jQuery Soap Ajax Request Example

var userName=’myUserName’;

var password=’myPassword’;

var soapenvHeader =
‘<soapenv:Header><wsse:Security xmlns:wsse=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd”&#8216; +
‘ xmlns:wsu=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd”>&#8217; +
‘<wsse:UsernameToken wsu:Id=”UsernameToken-6″> ‘+
‘<wsse:Username>’+userName+'</wsse:Username>’+
‘<wsse:Password Type=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText”>’+password+'</wsse:Password&gt; ‘ +
‘<wsse:Nonce EncodingType=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary”>sNuKHy0WlAszlbmjYz7i/g==</wsse:Nonce><wsu:Created>2014-10-02T17:15:57.362Z</wsu:Created></wsse:UsernameToken></wsse:Security></soapenv:Header>&#8217;;

function getRequestBody(zipcode, soapAction) {
// build SOAP request
var soadpenvBody =
‘<soapenv:Body>’+
‘<ajax:’+soapAction + ‘>’ +
‘<zipcode>’ + zipcode + ‘</zipcode>’+
‘</ajax:’+soapAction+’>’ +
‘</soapenv:Body>’;

var soapenvEnvelope =
getSoapEnvelop(soapenvHeader, soadpenvBody);
return soapenvEnvelope;
}

function getSoapEnvelop(soapenvHeader, soadpenvBody) {
var ret =  ‘<?xml version=”1.0″ encoding=”utf-8″?>’ +
‘<soapenv:Envelope ‘ +
‘xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; ‘ +
‘xmlns:ajax=”http://www.tibco.com/bs3.0/_BexlQEo4EeSHK8i-eh2cKg/AjaxServicesProcess&#8221; ‘ +
‘xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; ‘ +
‘xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/”>&#8217; +
soapenvHeader +
soadpenvBody +
‘</soapenv:Envelope>’;
return ret;
}

function sendAjaxRequest(urlInput,soapActionInput,requestBody, successCallback, errorCallback) {
$.ajax({
url: urlInput
,data: requestBody
,type: “POST”
,dataType: “xml”
,headers: {
SOAPAction: soapActionInput
}
,contentType: “text/xml”
,success:successCallback
,error: errorCallback
});
}