开发者

Authenticating REST requests in MVC 2

开发者 https://www.devze.com 2023-01-23 15:29 出处:网络
Hey SO, in the past few hours I was trying to get my head around RESTful services that can be served via asp.net MVC. Authentication is still something that doesn\'t seem to be covered in all those tu

Hey SO, in the past few hours I was trying to get my head around RESTful services that can be served via asp.net MVC. Authentication is still something that doesn't seem to be covered in all those tutorials and guides i was finding in the interwebs.

Currently we are using Forms Based Authentication in our existing MVC Application. As far as I understand we need to add Basic HTTP Authenticati开发者_开发问答on to be able to handle REST requests and user permissions connected to the user context. Is there any way to "mix" these two Authentication Modes in one Application?


I'm not sure if there's anything built in, but you can write your own. Something like:

var authHeader = Request.ServerVariables["HTTP_AUTHORIZATION"];
if (authHeader.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase))
{
    var authParams = Encoding.Default.GetString(Convert.FromBase64String(authHeader.Substring("Basic ".Length)));
    var arr = authParams.Split(':');
    var username = arr[0];
    var password = arr[1];
}   

If you're writing your own REST framework in MVC, you could have a base Controller class, and have a method similar to this that runs before each action to authenticate the caller.


Dave,

I understand your point. Membership framework uses cookie extensively for authentication. You pass your credentials to server, server validates them against user database and issue you an authentication cookie. Next time every call of urs contains this authentication cookie which server uses to authenticate and authorise the user. Now whole this workflow works seamlessly when you use browsers.

Now in your scenario, you can create an Action in a controller which validates credentials. You can pass credentials to this Action in either post/get data. You will have to save the authentication cookie in your code and include that each time when making a call to the server . You can override HttpWebRequest class to perform these steps and you can use same class in your code.

In case this is much of an overhead and you are looking for something like Web-Services sort of functionality, I will advice you to look into WCF Services / Ado.NET Data Services. These integrate with Membership framework more seamlessly and may be better suited to your results.

I hope this helps, thanks.


You can easily use ASP.NET membership framework with ASP.NET MVC RESTful services. See the following link for its implementation with MVC RESTful services.

http://msdn.microsoft.com/en-us/magazine/dd943053.aspx

In case you are not aware of membership framework use following link

http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx

I hope it helps, thanks

0

精彩评论

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