6

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:

  1. Add some sort of "[authenticate]" attribute to all webapi actions (or even better on global level)
  2. Create some sort of ssl certificate to the web service
  3. 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??)

Community
  • 1
  • 1
Avba
  • 14,822
  • 20
  • 92
  • 192
  • Your steps correct. What is your point in here, what problem you are facing? – cuongle Jan 28 '13 at 08:29
  • My question is how is this accomplished practically and not in idea :) – Avba Jan 28 '13 at 08:41
  • how do i add these authenticate attirbutes, how do i make sure that the pw passed to the server is secure and so on – Avba Jan 28 '13 at 08:41
  • You can refer this answer: http://stackoverflow.com/questions/11775594/how-to-secure-an-aspnet-mvc-web-api/11782361#11782361 by using HMAC authentication – cuongle Jan 28 '13 at 08:42

1 Answers1

12

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 the OnAuthorization function 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 your OnAuthorization method 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

public class PasswordAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            string password = actionContext.Request.Headers.GetValues("Password").First();

            // instead of hard coding the password you can store it in a config file, database, etc.
            if (password != "abc123")
            {
                // password is not correct, return 401 (Unauthorized)
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
        }
        catch (Exception e)
        {
            // if any errors occur, or the Password Header is not present we cannot trust the user
            // log the error and return 401 again
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }
    }
}

[PasswordAuthorize]
public class YourController : ApiController
{
}

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

netsh http add sslcert ipport=0.0.0.0:8000 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} 

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/


Community
  • 1
  • 1
Despertar
  • 21,627
  • 11
  • 81
  • 79
  • 1
    Thanks for the answer, Can you direct me to some resources for generating those certificates and binding them to the request? – Avba Jan 28 '13 at 08:39
  • 1
    Sure, it's a one-liner you call using netsh utility (for older os like XP you use httpcfg). You will want to add the certificate and it's private key to your certificate store first. I've appended the cmd and some additional references that should be useful to my answer. – Despertar Jan 28 '13 at 08:42
  • 1
    Thanks! Last small issue, how can I then add some sort of password and make sure that IIS will drop all requests without that in it? (I mean add some sort of global "check that every request which comes over https has this password in the request : https://www.myapi.com/mymethod?pw=123456) – Avba Jan 28 '13 at 10:23
  • 2
    I've updated my answer with a better example of how to override the authorize attribute for custom password checking. IIS does not drop the request, but returns a 401 to the user in case they cannot authenticate. – Despertar Jan 28 '13 at 20:01