Protect MVC4 C # webapi so that only my application can access it

I read a few posts here, but can't find a decent answer, hope someone can help.

I saw that you can add

[Authenticate]

for mvc controllers. This is reasonable in a website situation where people can log in, but I have an iOS app that communicates with a web service. I would like to restrict access only to my application.

I think the required "steps" are:

  • Add some attribute "[authenticate]" for all webapi actions (or even better globally)
  • Creating some kind of ssl certificate for web service
  • Add some kind of authentication method and hard code credentials to the application code.

How can this or similar be done using the mvc structure?

(PS: they saw messages like this , but this is very impractical, adding this logic to every part of the code action, and also what “problem” am I creating ??)

+5
source share
1 answer

There are some easy ways to authenticate yourself to your web service, and you don’t need to use anything fantastic or even follow some standards, such as OAuth or OpenID (not that it's bad, but it looks like you want to get in the door with something simple).

, , , AuthorizeAttribute ( , System.Web.Http, MVC). OnAuthorization . . , MVC Api Action System.Web.Http.AuthorizeAttribute - ?

, . - - MyID: [SomeRandomString]. OnAuthorization , , 401 ().

, , , https://, , /, , IIS, . , - HTTP .


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
{
}

- IIS, , " ", , http://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html


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} 

, - api https, http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web-api/


+10

All Articles