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/