开发者

Javascript request for JSON result in ASP.NET MVC 3 using Forms Authentication

I have an MVC 3 REST API that has a simple controller: ApiController. There is a method Foo in ApiController that takes some stri开发者_Python百科ng information in and returns a JSON result:

public class ApiController : Controller
{
    [HttpPost]
    public JsonResult Foo(string input)
    {
        ...
    }
}

I want to have a JQuery method call Foo with some user-entered data and display the result.

The catch here is that I want to check that the user is allowed access to Foo. What's the best way to go about this in ASP.NET MVC 3? I think the answer is to use SSL and basic authentication, but I have no idea what that would look like. Also, do I have to roll my own password hashing/salting or is there some way to just use Forms Authentication?

Edit: Note that I'm trying to create an API that third-party developers can use. For example, if someone writes a Rapportive-style browser plug-in that scans your Gmail, sends the text to Foo, and displays it in the browser.

Also, I believe just using Forms Authentication will send the username/password information in plain text, right? I'm not sure how to implement SSL to prevent this.


You could use FormsAuthentication and the [Authorize] attribute. So you might have a AccountController with a LogOn action which will be accessible only through HTTPS. This controller will allow clients to authenticate and get an authentication cookie which will be reused for accessing the API:

public class AccountController: Controller
{
    [HttpPost]
    [RequireHttps]
    public ActionResult LogOn(string username, string password)
    {
        // TODO: verify the credentials and emit an authentication cookie if valid
        // return some result (JSON?) to indicate whether the operation succeeded or
        // not
    }
}

then all that's left is to decorate your other controller actions that you want to secure with the [Authorize] attribute:

public class ApiController : Controller
{
    [HttpPost]
    [Authorize]
    public JsonResult Foo(string input)
    {
        ...
    }
}

So now a client will need to first call the LogOn action and fetch the corresponding authentication cookie in the response which will be sent along subsequent calls to your API.


You should be able to use the [Authorize] attribute to do what you want here. See the following details and example on MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

You can authorize specific users, or users within a specific Role.

The default Forms-based authentication provided when you create a new (non-empty) ASP.NET MVC project will enable you to authorize users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜