I am developing a WCF REST service where requests are authenticated using basic authentication over SSL. However, before I send the authentication challenge I want to ensure that the request is valid using a pre-shared API key. I do not want the key value passed in the URL so is a custom HTTP header the best solution? Something like X-APIKey: keyvalue.
I am authenticating the user’s credentials in a HttpModule:
public void OnAuthenticateRequest(object source, EventArgs eventArgs)
{
HttpApplication app = (HttpApplication)source;
if (!app.Request.IsSecureConnection)
{
app.Response.StatusCode = 403;
app.Response.StatusDescription = "SSL Required";
app.Response.End();
return;
}
string authHeader = app.Request.Headers[AUTH_HEADER];
if (authHeader == null)
{
app.Response.StatusCode = 401;
app.Response.End();
return;
}
ClientCredentials credentials = ClientCredentials.FromHeader(authHeader);
if (credentials.Authenticate())
{
app.Context.User = new GenericPrincipal(new GenericIdentity(credentials.Id), null);
}
else
{
DenyAccess(app);
}
}
That’s a good alternative (passing it in a header). You can then use a custom message inspector to validate that the shared key is present in all requests for a specific endpoint, as shown in the code below.