2

Quick question;

Giving the controller User and the and function Get someone could call;

mydomain.com/user/get and access the functionality over there.

What are the best practices to allow only my application to be able to call that?

Thanks

0

2 Answers 2

3

Decorating the Action Method with the [ChildActionOnly] attribute will ensure that the Action Method on a controller cannot be directly invoked by a user entering a URL. EG

 [ChildActionOnly]
        public ActionResult _CantNavigateHere()
        {
            return View();
        }  
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Judo,It works if the call is done from a controller. I call some controller funcitonality from jQuery using $.ajax, and when i do, if the controller action is decorated like you proposed i get a 500 error back. How can i be able to call this action from jquery and still have it decorated like that?
For ajax scenarios you will need to implement an [AjaxOnly] attribute, there is a simple demo here helios.ca/2009/05/27/… .
But does this mean that anyone could call it using ajax?
It would be a bit of a hack, but yes it could theoretically be called using Ajax. These filters are more for separation of concerns and consistency than security. If there are security issues with accessing the controller then the controller probably exposes too much. Perhaps post some more of your code.
Well, let's say that i have a controller called Save and an action called Transaction, and that i pass to that action a couple of string parameters; and i'm using jQuery ajax ($.ajax) to post back to the server, a pretty common scenario these days; i believe there's got to be a way to secure that, to allow only mu application to make use of that functionality, isn't it?
|
1

You can use the AntiForgeryToken with MVC3 and Ajax.

This is how I do it. (this isn't foolproof of course, but adds another layer of security)

On your view, anywhere, output:

@Html.AntiForgeryToken()

And in your Ajax call include this value in the post variables like:

$.post("/Controller/Action/",
                { 'id': var_id, '__RequestVerificationToken': $("input[name='__RequestVerificationToken']").val() }, 
                function (data) { /* handle request */ });

And in your Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Action(int id) {..}

Besides this, you can also do a check for the referring host and reject any host that doesn't match your domain. This can be spoofed, but again, is just another layer to add.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.