I’ve read some posts here, but can’t seem to find a decent answer, hope someone can help.
I’ve seen that you can add
[authenticate]
attributes to mvc controllers. This is reasonable in a web site situation where people can log in, but I have an iOS app communicating with a web service. I would like to restrict access only to my app.
I think that the “steps” that are needed are:
- Add some sort of “[authenticate]” attribute to all webapi actions (or even better on global level)
- Create some sort of ssl certificate to the web service
- Add some sort of authentication method and hard code the credentials into the app code
How can this or similar be accomplished leveraging the mvc framework?
(PS: have seen posts like this but it is very unpractical adding this logic to every piece of code action, also what kind of “challenge” would I create??)
There are some simple ways you can authenticate yourself to your web service, and you don’t have to use anything fancy or even follow some standard like OAuth or OpenID (not that these are bad, but it sounds like you want to get your foot in the door with something simple).
First thing you need to do is learn how to derive from
AuthorizeAttribute(the one in System.Web.Http namespace, not the MVC one). You override theOnAuthorizationfunction and put your authentication logic in there. See this for help, MVC Api Action & System.Web.Http.AuthorizeAttribute – How to get post parameters?Next decide how you want to authenticate. In the most basic form, you could do something like add a header to each web request called
MyID: [SomeRandomString]. Then in yourOnAuthorizationmethod you check the header of the request, if it is not the correct string you set the response status code to 401 (Unauthorized).If your service is self-hosted then you can bind a certificate to the port it is hosting on and use an https:// prefix and you now have secured the transport layer so people cannot see the id/password you are passing. If you are hosting in IIS you can bind a certificate through that. This is important as passing something like a password over plain HTTP is not secure.
Create Custom AuthorizeAttribute
Generate Self-Signed Certificate
Easiest way to generate a self-signed certificate is opening IIS, clicking server certificates, then ‘generate self-signed certificate’ as shown here, http://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html
Binding a certificate to a port
http://msdn.microsoft.com/en-us/library/ms733791.aspx
And here is an awesome tutorial on how to self-host a web api service over https, http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web-api/