Sencha Touch: Accessing a remote API that is under Basic Authentication

Posted on 2 Comments

ST makes it pretty straightforward to access webservices or APIs through its various data proxies and Ext.Ajax. But consuming an API protected under basic authentication can be tricky. Both data proxies and Ext.Ajax provide setUsername() and setPassword() methods, and they work fine on most browsers. But in my experience using these methods, I had big time face-palm moments in case of Safari, iOS, and some Android versions. When these methods are used, an ST app sets the Authorization header AND makes all API requests through URLs formed such as this:

http://user:passwd@www.server.com/api/user/2627

I’m not sure why this is such a big deal for some browsers, but they seem to get confused due to the presence of these two things — Authorization header and user:passwd URL.

The trick to solving the issue is to NOT use setUsername() and setPassword(), and instead set the HTTP headers yourself.

Data Proxies have a headers config.

someModel.getProxy().setHeaders({
	'Authorization': 'Basic ' + btoa(username + ':' + password)
});

Ext.Ajax has a defaultHeaders config.

Ext.Ajax.setDefaultHeaders({
	'Authorization': 'Basic ' + btoa(username + ':' + password)
});

2 thoughts on “Sencha Touch: Accessing a remote API that is under Basic Authentication

  1. Nice post, thanks. You might be interested in how to use HTTP Basic Auth with raw javascript XmlHttpRequest interface. See http://zinoui.com/blog/ajax-basic-authentication

Leave a Reply

Your email address will not be published. Required fields are marked *

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