I am trying to create a relatively simple RESTful self-service service with WCF, but I wanted to add custom authentication. To this end, I tried to override UserNamePasswordValidator . Unfortunately, although this is called to verify the username / password combination, if the username / password does not pass, the server returns 403 Forbidden, rather than 401 Unauthorized, as I expected. This will cause a big problem, because if the user fails to authenticate for the first time, they will not be asked to re-enter the credentials if they do not restart the browser. So what am I doing wrong?
This is what I have so far:
(The actual ServiceContract contains a single method that returns a string)
class Program { static void Main(string[] args) { WebServiceHost host = null; try { host = new WebServiceHost(typeof (MyService)); const string uri = "http://127.0.0.1/MyService"; var wb = new WebHttpBinding { Security = { Mode = WebHttpSecurityMode.TransportCredentialOnly, Transport = {ClientCredentialType = HttpClientCredentialType.Basic} } }; var ep = host.AddServiceEndpoint(typeof (IMyService), wb, uri); host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new PasswordValidator(); host.Open(); Console.WriteLine("Press any key to terminate"); Console.ReadKey(); } finally { if (host != null) host.Close(); } } } public class PasswordValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (null == userName || null == password) throw new ArgumentNullException(); if (userName == "Test" && password == "Password") return; throw new WebFaultException(HttpStatusCode.Unauthorized); } }
I have already taken note of this other, similar question , but not one of the answers posted there actually works. I hope that a more precisely defined version of the question will give some better answers.
source share