问题描述:

I am new to developing API's and have built ASP.NET web api capability into an existing MVC project of mine. I am going to want clients to have the ability to send JSONs of multiple object instances that I can persist to my DB but currently the API consists only of the Values template that the framework provides and I'd like to sort out securing it now before moving forward developing the API fully:

[Authorize]

public class ValuesController : ApiController

{

// GET api/<controller>

public IEnumerable<string> Get()

{

return new string[] { "value1", "value2" };

}

// GET api/<controller>/5

public string Get(int id)

{

return "value";

}

// POST api/<controller>

public void Post([FromBody]string value)

{

}

// PUT api/<controller>/5

public void Put(int id, [FromBody]string value)

{

}

// DELETE api/<controller>/5

public void Delete(int id)

{

}

}

The Authorize tag requires a user to log in on my site at the moment, and I am confused as to how my API could be called programmatically in this instance.

I am wanting to secure the api whereby a client wanting to use it will have to provide their unique API key in order to access functionality. Furthermore I would like to use this API key to establish which user has called the API so that I can respond to them using only their data.

What are the steps involved in putting this in place from the early starting point I'm at (just having integrated the Web Api functionality)?

I've been looking at and getting confused by HMAC authentication, although this does seem similar to what I'm after it seems quite complicated to implement (maybe just because I'm in a new area here) and I thought there must be a simpler way to achieve what I want?

网友答案:

A quick solution is to extend AuthorizeAttribute and define your authentication logic there. See this SO question for an example.

A little bit more modular approach is to create an authentication filter. See ASP.NET docs here. This way you can separate authentication and authorization.

As for HMAC vs Basic authentication, I would go with the simpler Basic authentication is security is not a key component of your system. This way you can ship v1.0 faster.

相关阅读:
Top