Category Archives: JavaScript

CORS and HTTP 302 redirect responses

CORS Filter
Earlier this week a user of the CORS Filter library asked why his browser app wasn’t able to connect to his web service despite it having Cross-Origin Resource Sharing (CORS) enabled.

Investigation of the problem showed that his XHR was not landing on the CORS-enabled URL directly, but was being redirected to it through an HTTP 302 (redirect) response.

So bear in mind that the redirecting URL must also include an Access-Control-Allow-Origin header, else the browser will stop right there with its attempted cross-domain request.

JSON-RPC 2.0 Base flies with the new JSON library

JSON-RPC 2.0Two years after its initial release the JSON-RPC 2.0 Base library switches to a new package for representing and parsing JSON messages. The result is 2x to 4x times faster performance in JSON-RPC message parsing!

Back in 2009 I chose JSON Simple for its simple and relatively non-invasive model for representing and mapping JSON entities to Java primitives and objects. Performance was also relatively good against the alternatives, so JSON Simple became the natural choice for the JSON-RPC 2.0 Base classes. JSON Simple development became stale with time however, and more than 2 years passed without any new releases or fixes to reported bugs. This, I suspect, must have led to the user community becoming somewhat frustrated and a fork imminent.

A fork of JSON Simple did indeed arrive, in May this year, initiated by Uriel Chemouni and named JSON Smart. Initial tests showed considerable performance gains and after some email exchange with Uriel which resulted in the addition of strict JSON parsing, JSON Smart became the new library for JSON-RPC 2.0 Base.

So what do you gain with the new release?

JSON-RPC message parsing is sped up 2.4 times for the reusable JSONRPC2Parser and 3.8 times for the static parse methods.

Parse performance for JSON-RPC 2.0 messages

Moreover, the difference in terms of performance between the static parser and the instance parser is almost negligible, which means that for apps like servlets there is no need to pool parsers in order to speed up request processing.

Thanks for Uriel for making this great piece of software!

In the next few days Json2Ldap and the other products in the NimbusDS line will receive the new library, so expect more good news!

Detecting CORS support in a browser

I’m using the following JavaScript function to detect whether a browser has support for Cross-Origin Resource Sharing (CORS) XHR.

function browserSupportsCors() {

	if ("withCredentials" in new XMLHttpRequest())
		return true;	
	else if (window.XDomainRequest)
		return true;
	else
		return false;
}

The XDomainRequest object is specific to IE 8 and IE9, other browsers, including IE 10, extend the existing XMLHttpRequest.

I use this piece of code in the Json2Ldap directory Ajax demo which I posted the other day.

jQuery still has no complete and robust plugin for CORS support. I hope this situation will change soon as browser support for CORS has passed 80%.

PS July 2012: Update of the CORS detection code to handle IE 9 better.

JSON-RPC 2.0 Base with thread-safe parsing

JSON-RPC 2.0Just when you think a piece of software has stabilised and there’s nothing more to add or change and something crops up to disturb this 🙂

The other day I received a report by Giancarlo Barresi, who had observed concurrency problems with the JSON-RPC 2.0 Base library under heavy load. It turned out that my message parsing was not thread-safe, to which today I released a fix under version 1.15. To those of you who are new to my blog, JSON-RPC 2.0 Base is a simple Java library for parsing, representing and serialising JSON-RPC 2.0 messages.

Giancarlo also pointed me to a more efficient JSON parser implementation, called JSON Smart, which is interface compatible with the currently used JSON.simple, but with better performance. JSON Smart’s benchmarks look impressive on paper, but I want to do some testing myself before I commit to a change in the underlying JSON library.

I have also noticed that JSON.simple development has virtually stopped now, despite there being a number of outstanding enhancement suggestions and bug reports. Which is another reason to consider switching to JSON Smart.

Stay tuned!

Vladimir

Search filter checking method added to the LDAP web service

Json2Ldap iconThe latest 1.8.1 release of the directory web service Json2Ldap adds a new JSON-RPC method for validating search filters. It can be used for example to check user input filter strings before making an actual ldap.search request.

This is a simple utility method that takes just one parameter – the filter string. Note that an LDAP connection is not required for this operation, so no CID (connection identifier) needs to be passed.

Example JSON request:

{ "method"  : "ldap.util.isValidFilter",
  "params"  : { "filter" : "&(objectClass=person)(givenName=Alice)" },
  "id"      : "0001",
  "jsonrpc" : "2.0" 
}

And here is the resulting JSON response indicating the filter was correct:

{ "result"  : true,
  "id"      : "0001",
  "jsonrpc" : "2.0" 
}

With this the “static” utility methods of Json2Ldap become five. The other served requests are:

The online Json2Ldap API docs have full details on these JSON calls.

JsWorld roadmap for 2011

JsWorld iconHere is a quick roadmap for 2011 for JsWorld, the Javascript library for currency, numeric and date/time l10n:

The core logic and API are pretty solid and settled now. No planned changes.

The locale database is scheduled for a small update in summer. At present it is based on Unicode’s CLDR 1.9 which supports over 300 locales, 200 countries and 100 currencies. Earlier this year there was a minor 1.9.1 release, but the fixes introduced there have no effect on number, date/time and monetary formatting. According to the tentative schedule published on the Unicode page a new major 2.0 release is planned for the end of May. Once the new locale data arrives I’ll regenerate the JsWorld database and put the new version as 2.4.1 up.

Otherwise I’m pretty busy these days, attending to various events here in London and also bringing the final bits of the NimbusDS.com website together. Nimbus DS is my latest venture to provide developers and integrators with specialised directory service solutions for web and cloud applications. This will become the new home of the Json2Ldap gateway / proxy, as well as of the newer JsonSSO and AuthService products.

How to debug CORS requests with Firebug

CORS FilterFirebug, the indispensable Firefox add-on for serious developers, is great for debugging web apps that make use of the new CORS mechanism for cross-domain requests. The acronym CORS stands for Cross-Origin Resource Sharing and was developed by a group of web activists to address the issue of making browser cross-domain requests in a standards-compliant way. The goal is to make CORS an official W3C standard. As of 2010 most browsers such as FF, IE, Chrome and Safari support it.

My first encounter with CORS was during the development of Json2Ldap, a smart piece of software designed to turn one or more LDAP directories into a web friendly JSON-RPC service. Json2Ldap turned out to be an excellent case for CORS as the web service had to be capable of serving cross-domain requests. Later I span off the server-side CORS code into a project on its own, called CORS Filter. It provides a generic servlet filter which can be retrofitted to any existing Java web app to make it cross-domain XHR capable.

Firebug has an excellent network activity monitor which can be used to reveal the CORS-specific conversation between browser and server during a cross-domain XHR. This is great for understanding how the protocol works, particularly the behaviour of simple/actual vs. pre-flight CORS requests.

To observe a CORS request in action you need a relatively recent version of Firebug (e.g. 1.6). Click on the “Net” tab and then on the “XHR” tab, then launch your cross-domain request.

How to load the Firebug Network Monitor

For a simple/actual CORS request Firebug will then display the following headers:

Simple/actual CORS request

Note the Origin header which the browser inserted to identify the domain from which the HTML page originated. The server checks the Origin value and responds accordingly, by either allowing or denying the request.

Simple CORS response

If the server allowed the origin it replies with an Access-Control-Allow-Origin header that contains a verbatim copy of the Origin header value or * (meaning any origin). The server may also include optional CORS response headers, such as Access-Control-Allow-Credentials (to tell the browser that it accepts cookies) or Access-Control-Expose-Headers (to tell the browser which custom headers are safe to expose to the requesting script).

CORS also has the so-called preflight request which browsers can send using HTTP OPTIONS prior to the actual CORS request to query the CORS settings of a particular HTTP server, such as the supported HTTP methods, custom headers, etc.

Tip: How to simulate a cross-domain request if you have just a single HTTP server to play with: Create a host alias of your web server and reload the requesting page using the alias URL.

Finally, today I learned that the Jetty 7 web server has a CORS filter implementation similar to the one I developed few months ago. On first inspection the only notable difference is that it doesn’t support request tagging and the Access-Control-Expose-Headers response header.

JsWorld 2.4

JsWorld iconThis is a notification of the release of JsWorld 2.4. The new version keeps the core library logic the same. The only updates are to the locale definitions which now match the latest country data released by the Unicode Consortium (CLDR 1.9 from 2010-12-01). The JavaScript library now supports numeric, currency and date/time formatting + parsing in 341 world locales. Click here to see the complete list of languages, countries and currencies included in JsWorld 2.4.

Existing license holders were notified where they can download the update for no additional charge. If you haven’t received your email or have any questions or comments about this update – get in touch with me.

Json2Ldap 1.6

Json2Ldap iconOctober saw a release of Json2Ldap version 1.6 which brings updates in three areas: the web API, addition of CORS support and library upgrades. The software is now being put to serious use and I’m glad to see its popularity pick up, despite having no dedicated marketing effort behind it. I must say the whole concept of web-enabling LDAP directories with a simple JSON-RPC API is one very attractive proposition for companies offering web services, such as social networking or SaaS, as a way to provide web-exposed user storage API and authentication in a standard and web friendly fashion.

Cross-Origin Resource Sharing (CORS)

Json2Ldap now includes support for the CORS protocol that allows browsers to make cross-origin XHR requests, in the spirit of modern Ajax/Web 2.0 applications where a web application uses data and methods from several sources. CORS is now supported by most mainstream browsers, such as Firefox, IE, Chrome and Safari. The protocol is implemented by a highly flexible and configurable servlet filter, which I also offer as a separate add-on product to customers who want to add CORS to their own Java web services.

Json2LDAP API changes

Json2Ldap 1.6 also makes some minor changes to the web API, in order to make it more generic and allow for future implementation of LDAP extensions, such as password expiration controls.

  • Connection identifiers (CIDs), returned by the ldap.connect call, are now represented by standard GUIDs (or UUIDs).
  • ldap.connect returns an object where the CID values is put into a separate field.
  • ldap.simpleBind and ldap.anonymousBind return empty object instead of null; this is to allow for new optional result fields in future without breaking backward compatibility.

Configuration

New configuration parameter json2ldap.clients.responseContentType which sets the MIME type of Json2Ldap responses.

Library upgrades

Many of the underlying libraries were also upgraded to recent stable versions:

  • UnboundID SDK JAR to 1.1.6.
  • JsonRpc2-Base JAR to 1.11.
  • JsonRpc2-Proc JAR to 1.1.
  • Property Util to 1.2.

Also, the JSON-RPC 2.0 Shell tool was upgraded to version 1.4.

Roadmap

What’s ahead? For version 1.7 I plan to add support for the simple page results control (RFC 2696). I also consider implementing the SASL external bind control, as defined in RFC 4422.

Sending JSON-RPC 2.0 requests with jQuery

Dispatching JSON-RPC 2.0 – style requests with jQuery is easy. Just use the jQuery.post() method:

var url = "http://rpc-service.net/jsonrpc2/";

var request = {};
request.method = "ldap.search";
request.params = {};
request.params.CID = "45d0677d-a336-463b-ad99-c82137d03a00";
request.params.baseDN = "ou=people,dc=example,dc=com";
request.params.scope = "ONE";
request.params.filter = "(givenName=John)";
request.id = 1;
request.jsonrpc = "2.0";

function displaySearchResult(response) {

        if (response.result)
                alert(response.result);

        else if (response.error)
                alert("Search error: " + response.error.message);
};

$.post(url, JSON.stringify(request), displaySearchResult, "json");

The above example assumes that you have jQuery 1.4+ and the json2 encoder/decoder installed.

For those of you who are new to JSON-RPC 2.0 – this is the second release of the simple remote-procedure call (RPC) protocol using JSON messages. I’ve incorporated it in a number of my own software products, the idea being that it would be better for all of us – customers and developers alike – to standardise on a common JSON protocol for web services, instead of every one coming up with their own ad-hoc JSON protocol. I’ve spun off my minimalist Java implementation into a separate client/server library.

The JSON-RPC community has its forum at Google groups: http://groups.google.com/group/json-rpc