I have made a simple RESTful Web Service (GET-only, for now) using the Microsoft ASP.NET MVC 4 ApiController
.
Now I'm looking for the right way of implementing an authorization system for the service. I know I don't want to use the built-in FormsAuthentication
, since I don't want to have a unique login page for all the applications using my WS; moreover, that breaks the RESTful paradigm, forcing a redirection and not notifying the client with the proper 401
status code.
So I have disabled FormsAuthentication
deleting the following lines from my web.config
:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
and adding the following:
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
</modules>
I already have an ApiController
for managing the User login, which basically checks the credentials against my database and returns the user or a 401
if the credentials are not valid.
I have read that I have to implement the Membership
and Authorization
API, but I found nothing that helps me doing from scratch.
Do you have any ideas? Do I need to manage cookies and authcodes on the database or is there a similar class to FormsAuthentication
that does it for me?
You could write a custom message handler to handle authentication. Dominick Baier wrote en excellent series of blog posts which delves into the details.
I found a solution, I just basically used the workaround shown in the example by Microsoft.
Since I didn't like the "Content moved here" in my 401 response, I have edited the OnEndRequest
method this way:
private void OnEndRequest(object source, EventArgs args)
{
var context = (HttpApplication)source;
var response = context.Response;
if (context.Context.Items.Contains("__WEBAPI:Authentication-Fixup"))
{
response.StatusCode = (int)context.Context.Items[FixupKey];
response.RedirectLocation = null;
// Clear the page content, since I don't want the "Content moved here." body
response.ClearContent();
}
}
References:
Checkout this project on github. They have developed some classes, with examples, for adding security to the ASP.NET Web API. One of the security models supported is basic authentication, which seems to be what you are describing in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With