Announcement Announcement Module
Collapse
No announcement yet.
Securing controller method called via Ajax (jQuery) Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Securing controller method called via Ajax (jQuery)

    I have a button on a webpage which is used to execute a task in the backend of my application. If the task is started successfully then I would like a report back to the user saying execute successful (I have all this working so far). The person doing the execute should only be able to do so if they have the correct permission which is stored in the user object.

    Problem:
    I am unable to catch the access denied exception and report back to the javascript click function on the webpage before the spring security takes it and sends the generic exception page to the browser. Please see the following for further details...

    I have a javascript function using jQuery ajax() which is triggered by a button onClick() and is as follows in my jsp:
    Code:
    function ajaxExec() {
        $.ajax({
       	  type: "POST",
    	  url: "<c:url value="/my/exec/url" />",
    	  cache: "false",
    	  success: function(response){
    	    $('#Info').html(response);
    	  },
    	  error: function(e){
    	    alert('Failed to Execute: ');
    	  }
    	});
      }
    This sends the url request through to the controller which has a method to run the execute:
    Code:
        @ResponseBody
        @RequestMapping(value = "/my/exec/url", method = RequestMethod.POST)
        public String executeTask(final Model model, BindingResult bindingResult) {
            // do the execute
            String returnString = "Task Executed";
            return returnString;
        }
    This works fine and will return the string to the JavaScript function where the 'Task Executed' message is displayed on page.

    The problem is that I am now trying to secure the controller method with a Spring Security annotation as follows:
    Code:
    @PreAuthorize("@securityTests.isAuthorisedToExecute(#model[fooObj], principal)")
    When the authorisation check fails this throws the AccessDenied exception which is then caught by the 'SimpleMappingExceptionResolver' in the servlet.xml and results in the default error view being displayed.

    After spending all afternoon trying to find a solution to this I am stuck and in need of help!

    I'm starting to think that maybe I have not implemented the ajax call in the correct way.

    Please could someone help push me in the right direction with this, I would really appreciate it!

    Thank you!

  • #2
    why dont you override SimpleMappingExceptionResolver to formulate a json authentication failure response, basically a json version of 403.

    Comment

    Working...
    X