The most common way to provide security in a Web API application is through the usage of the built-in [Authorize] attribute. You can read more about authentication in Web API here. The Authorize attribute depends upon the ASP.NET membership or identity framework. Either the membership system or the identity system can be used. I would recommend the identity framework since it is newer and the model that will be supported going forward. You can read more about the ASP.NET identity framework here. A sample application that implements authorization and authentication using the ASP.NET identity framework can be found here. I will provide a few common examples.
To restrict access to all controllers/routes globally:
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new AuthorizeAttribute());
}
To restrict access on individual controllers:
// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
//Allow anonymous access on Get, but restrict all other actions
[AllowAnonymous]
public HttpResponseMessage Get(int id) { ... }
public HttpResponseMessage Post() { ... }
}
To restrict access on specific actions:
public class ValuesController : ApiController
{
// Anonymous access is allowed on Get
public HttpResponseMessage Get() { ... }
// Require authorization for Post.
[Authorize]
public HttpResponseMessage Post() { ... }
}
To restrict access to a specific role/user:
public class ValuesController : ApiController
{
// Anonymous access is allowed on Get
public HttpResponseMessage Get() { ... }
// Require specific user access on Post
[Authorize(Users="Bob,Joe")]
public HttpResponseMessage Post() { ... }
// Require specific role access on Delete
[Authorize(Roles="Administrators")]
public HttpResponseMessage Delete() { ... }
}