1

We are developing an Ajax application and are utilizing the jQuery Address plugin to load the various pages of the application So the urls for our site look like: www.app.com#/SomeController/SomeAction. Navigating to such a url loads the default route for the application and then jQuery Address is utilized to load the SomeController/SomeAction url into a div on the page.

The problem is that the user can still access www.app.com/SomeController/SomeAction (no hash sign) directly by typing the url in the browser. How do we prevent the user from being able to access the pages directly and require that they have the hash sign in there to make sure the pages are loaded via Ajax request?

Nick Olsen
  • 6,299
  • 11
  • 53
  • 75

3 Answers3

1

You could create a filter that checked request.isajaxrequest(). You reject any requested that aren't, apart from on the default route.

I'm not sure if it's the best way though.

Simon Halsey
  • 5,459
  • 1
  • 21
  • 32
1

Create a route to add prior to your default route, like so:

routes.MapRoute(
    "404 non-hashed",
    "{*fullPath}",
    new { controller = "Error", action = "Show404" },
    new { fullPath = @"^(?!#).+" }
);

This route will handle any request which does not start with a hash character. Any request starting with a hash character will fail the route constraint, and will go on to your default route.

Create a controller and action to show a 404 page, or some custom error page, and you are set.

counsellorben
  • 10,924
  • 3
  • 40
  • 38
0

counsellorben is correct, you can do routing tricks to try to limit the way legitimate clients or apps request a particular resource but you’ll never be able to protect yourself from the forging (With fiddler or another tool). The approach proposed by counsellorben is only useful to potentially avoid user confusion and limit the “API” area of an app. Of course, you shouldn’t actually have an app that only depends on # deep links because that causes problems with SEO etc. But that’s a different discussion.

Another approach, rather than a filter, you can add the following to your action method

if (this.HttpContext.Request.IsAjaxRequest() != true)
            return RedirectToAction("Index");

standard practice here to give the anchor an empty or dummy href property and to have the click event perform the AJAX callback? That way, if a user copies the hyperlink he is just automatically given the correct URL.

RickAndMSFT
  • 20,912
  • 8
  • 60
  • 78
  • Thanks for the comment. I completely agree with the SEO problem this could cause but all of these pages will not be crawled by a bot as the user must be authenticated to access the application. – Nick Olsen Nov 01 '11 at 03:02