本文介绍了从 WCF UserNamePasswordValidator 正确捕获 SecurityTokenException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.usernamepasswordvalidator.aspx 如果用户名或密码错误,应该抛出 SecurityTokenException.这工作正常,但不是得到 SecurityTokenException 我得到的是 MessageSecurityException 并且我传递的文本消息在某处丢失了.我不是在发送故障细节".

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.

推荐答案

快速查找(为什么我之前没有看到...),我在问题中提供的链接指向了http://msdn.microsoft.com/en-us/library/aa702565.aspx

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

它与第一个示例有些不同,如果您想提供消息详细信息,它有关于使用 FaultException 而不是 SecurityTokenException 的注释.

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");
    }
}

客户端捕获的异常现在包含一个内部异常类型 FaultException 和我想公开的文本消息.

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

这篇关于从 WCF UserNamePasswordValidator 正确捕获 SecurityTokenException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 01:32