SpringSecurity: Authenticating & Authorizing AJAX Requests (Client-Side Implementation)

This is the last part of SpringSecurity: Authenticating & Authorizing AJAX Requests. In first part, we discussed some background theory. In second part, we went through server-side implementation. Now in this post, we will go through client-side implementation. This implementation will be based upon jQuery, but I hope you can easily translate it in your favorite framework.

All you need to do is to create a new JS file and copy/paste following code into it. Afterwards, you need to include that JS file right after the point where you included your jQuery file.

    // Save reference to actual jQuery ajax function
    var $_ajax = $.ajax;
        // override jQuery ajax function with a custom implementation
	$.ajax = function(options){
		var originalSuccess,
		// if a success callback is included
		if (options.success) {
                        // save reference to original success callback
			originalSuccess = options.success;
			success_context = options.context ? options.context : $;
                        // define a custom success callback
			mySuccess = function(data) {
                                // check authentication & authorization
                                if (data['access-denied']) {
                                    if (data.cause==='AUTHENTICATION_FAILURE') {
                                        alert('You have been logged out of the system, please login again.');
					window.location.href = contextPath + '/';
                                    } else if (data.cause==='AUTHORIZATION_FAILURE') {
                                        alert('You are not authorized to request this resource.');
                                // call original success callback							
				originalSuccess.apply(success_context, arguments);
                        // override success callback with custom implementation
			options.success = mySuccess;
                // call original ajax function with modified arguments
		$_ajax.apply($, arguments);

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

2 thoughts on “SpringSecurity: Authenticating & Authorizing AJAX Requests (Client-Side Implementation)”

Leave a Reply

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