【问题标题】:Custom UserNamePasswordValidator with detailed return info?带有详细返回信息的自定义 UserNamePasswordValidator?
【发布时间】:2012-06-30 21:27:37
【问题描述】:

我开始通过 WCF 为我的 c#/.net 应用程序开发 REST API。

我通过自定义的 UserNamePasswordValidator 使用基本 HTTP 身份验证。它验证我的 API 方法。

它基于这个示例代码,我可以毫无问题地让它工作:

public class CustomUserNameValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {

        if (null == userName || null == password)
        {
            throw new ArgumentNullException("You must provide both the username and password to access this service");
        }

        if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
        {
            throw new FaultException("Unknown Username or Incorrect Password");
        }
    }
}

当身份验证失败时,我只能向客户端发送“401 Unauthorized”。我知道这是应该的方式,但是在这种情况下,是否有可能以某种方式将一些详细信息发回给我的来电者?一些自定义的错误消息或更详细的信息。如果没有,我的客户端只有身份验证失败的http信息,在我的情况下还不够。

【问题讨论】:

    标签: wcf http authentication rest


    【解决方案1】:

    也许你应该使用 WebFaultException ,在我的例子中我是这样使用的:throw new WebFaultException<string>("Bad Request", HttpStatusCode.Unauthorized);

    【讨论】:

    • UserNamePasswordValidator 是 Authentication 可扩展性而不是 Authorization 但使用 HttpStatusCode.Unauthorized 仍然是正确的,因为 401 Unauthorized 实际上暗示了 HTTP RFC2616 10.4.2 indicates b>身份验证.
    猜你喜欢
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多