Correctly catch SecurityTokenException from WCF UserNamePasswordValidator

According to the UserNamePasswordValidator sample at http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.usernamepasswordvalidid.aspx, you should throw a SecurityTokenException if the username or password is incorrect. This works fine, but instead of getting a SecurityTokenException, I get a MessageSecurityException , and the text message that I'm sending is somewhere lost. I do not send "parts in trouble."

Any ideas how to catch these errors correctly? I'm going to try a few things myself and see if I can fix this.

+3
source share
1 answer

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

It is slightly different from the first sample and has a comment about using a FaultException instead of a SecurityTokenException if you want to provide information about the message.

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 client exception thrown now contains an internal exception of type FaultException with the text message I want to open.

+6
source

Source: https://habr.com/ru/post/1708249/


All Articles