RESTFul Authentication with WebAPI

SB2055 picture SB2055 · Apr 4, 2013 · Viewed 10.7k times · Source

I have a web service built with WebAPI that accepts JSON requests and responds accordingly. The core architecture is built but there isn't any authentication/authorization.

After a lot of googling and poking around sample projects, I'm not sure where to start. I've found a ton of material from 2008 and 2009 but not a whole lot of recent guides/workflows for WebAPI / single page apps. I think the workflow should be as follows:

  1. Check to see if the user is logged in: How can this be done with javascript? Do I send a cookie to my webAPI? If so, do I send that cookie as a parameter in the body of the request?

  2. Let the user log in / register: How is this data encrypted/decrypted? Surely I can't be sending passwords over the wire... is this where SSL comes in?

  3. Provide them with access to what they have rights to access: I think I got this - I can just authorize in the controllers on a per-request basis.

Any info would be awesome.

Answer

yoneal picture yoneal · Apr 4, 2013

Basically you need a token based authentication or authorization. If you are referring to the ASP.NET WebAPI, the following project will be a great place to start: http://thinktecture.github.com/Thinktecture.IdentityModel.45/

Even if you are not using ASP.NET WebAPI, the following video is a great introduction on how to provide authentication/authorization on RESTful web services: http://vimeo.com/43603474

To answer some of your questions:

Check to see if the user is logged in: How can this be done with javascript? Do I send a cookie to my webAPI? If so, do I send that cookie as a parameter in the body of the request?

You can use a cookie but I normally use the header in order to avoid common XSRF attacks. Cookies are automatically included whenever a http request is sent from the browser.

is this where SSL comes in?

Yes. If you are going to go ahead with the token based approach, you can use a separate server (Identity Server) to do the authentication for you.