Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly catch SecurityTokenException from a WCF UserNamePasswordValidator

Tags:

wcf

According to the UserNamePasswordValidator sample on http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.usernamepasswordvalidator.aspx one should throw a SecurityTokenException if the username or password is wrong. This works fine, but instead of getting the SecurityTokenException I'm getting a MessageSecurityException and the text message I'm passing is lost somewhere. I'm not sending "details in faults".

Any ideas how to properly catch these errors? I'm going to try a few things myself and see if I can get it right.

like image 694
Johan Danforth Avatar asked Mar 01 '23 18:03

Johan Danforth


1 Answers

Quick find (why didn't I see if before...), the link I provided in the question pointed to another sample at http://msdn.microsoft.com/en-us/library/aa702565.aspx

It's somewhat different from the first sample, and has a comment about using FaultException instead of a SecurityTokenException if you want to provide message details.

public override void Validate(string userName, string password)
{
    if (null == userName || null == password)
    {
        throw new ArgumentNullException();
    }

    if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
    {
        // This throws an informative fault to the client.
        throw new FaultException("Unknown Username or Incorrect Password");
        // When you do not want to throw an infomative fault to the client,
        // throw the following exception.
        // throw new SecurityTokenException("Unknown Username or Incorrect Password");
    }
}

The exception caught on the client now contains an inner exception of type FaultException with the text message I want to expose.

like image 118
Johan Danforth Avatar answered Apr 07 '23 21:04

Johan Danforth