wcf


30
Apr 12

wcf rest interface with proper validation status code

I’ve been working on a self-hosted WCF REST service that supports HTTP authentication. I worked my way through all the fun bits, but near the end I ran into an issue with WCF’s handling of SecurityTokenExceptions in my custom UserNamePasswordValidatior. Instead of returning the expected 401 Unauthorized response code, I ended up with a 403 Forbidden┬áresponse. Not all at what I wanted, nor within HTTP spec.

After searching around, and around, it turns out this was a known issue that Microsoft decided to hotfix with an interesting workaround. To fix the problem, all I needed to do was add an item to the exception I was throwing’s data dictionary, indicating what HTTP response code I really wanted it to return.


public override void Validate(string userName, string password)
{
 if (string.IsNullOrEmpty(userName) | string.IsNullOrEmpty(password))
 throw new ArgumentNullException();

if (string.Compare(userName, "testuser1") != 0 || string.Compare(password, "testpassword1") != 0)
 {
 SecurityTokenException ex = new SecurityTokenException();
 ex.Data["HttpStatusCode"] = HttpStatusCode.Unauthorized;
 throw ex;
 }
 else
 {
 SecurityTokenException ex = new SecurityTokenException();
 ex.Data["HttpStatusCode"] = HttpStatusCode.Unauthorized;
 throw ex;
 }
}

Not the most elegant solution in the world, but it at least gets the job done.