Digest access authentication in Titanium

Blijkbaar is veiligheid geen prioriteit bij appcelerator en implementeren ze wel basic authentication maar geen digest…
Iemand heeft hen dat ooit al wel eens gezegd bij wijze van feature request maar de priority daarvoor is “low”.
Eitherway, dan maar zelf proberen op te lossen:

	// Let's try to make a connection
	var request = Titanium.Network.createHTTPClient();
	
	request.onload = function() {
		// Because we're using digest authentication
		// we won't get anything here yet
		// but getting a 401 error instead
	};

	request.onerror = function(e) {
		Titanium.API.info("IN 'normal' ERROR: " + JSON.stringify(e));
		if (this.status == 401) {
			wwwAuthString = "" + this.getResponseHeader("WWW-Authenticate");
			// Get all www-Authenticate from the header
			var wwwAuthArray = Array();
			wwwAuthArray = wwwAuthString.split(",");
			var nonceArray = Array();
			// Get the nonce part
			nonce = "" + wwwAuthArray[2];
			// And get rid of nonce=
			nonceArray = nonce.split('"'); // split on "
			nonce = nonceArray[1]; 
			Ti.API.info('nonce = ' + nonce);
			
			// And try again
			var req2 = Titanium.Network.createHTTPClient();
			req2.onload = function(e) {
				alert("SUCCES!: " + JSON.stringify(e));
				Titanium.API.info("In success mode: " + this.responseText);
				// DO SOME OTHER STUFF	
			};
			req2.onerror = function(e) {
				alert("ERROR req2 " + e.error);
			}
			req2.setTimeout(10);
			req2.setRequestHeader("Content-Type","application/json");
			// open the client
			req2.open('GET', 'http://host.tld/path');
			// Populate all vars for digest authentication
			var realm = "REST API";
			var uri = "/path";
			var qop = "auth";
			var nc = '00000002'; // This shouldn't be a fixed value
			var cnonce = "0a4f113b"; // Idem ditto
			var A1 = Ti.Utils.md5HexDigest('username' + ':' + realm + 'password');
			var A2 = Ti.Utils.md5HexDigest('GET'+':'+ uri);
			var resp = Ti.Utils.md5HexDigest(A1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + A2 );
			// Add authentication'
			var authstr = 'Digest ' + resp; 
			req2.setRequestHeader('Authorization', authstr);
			// send the data
			req2.send();
		}
	};
	
	request.setTimeout(10);
	request.setRequestHeader("Content-Type","application/json");
	// open the client
	request.open('GET', 'http://host.tld/path');
	// send the data
	request.send();

Ik ben er in geslaagd data van de server terug te krijgen die noodzakelijk is voor digest authentication, maar wanneer ik die data naar de server terugstuur loopt het mis en krijg ik alsnog een error. Moest je toevallig een oplossing hiervoor hebben of deze code verder uitpluizen: Let me know 😉

Leave a reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.