Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure MVC4 c# webapi so that only my app can access it

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??)

like image 933
Avner Barr Avatar asked Jan 28 '13 08:01

Avner Barr


1 Answers

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/


like image 109
Despertar Avatar answered Nov 14 '22 23:11

Despertar