gpt4 book ai didi

c# - 为什么我的自托管 WCF 服务返回 403 Forbidden,而不是 401 Unauthorized?

转载 作者:太空狗 更新时间:2023-10-29 21:28:54 25 4
gpt4 key购买 nike

我一直在尝试使用 WCF 创建一个相对简单的自托管 RESTful 服务,但我想添加自定义身份验证。为此,我尝试覆盖 UserNamePasswordValidator。不幸的是,虽然调用它来验证用户名/密码组合,但如果用户名/密码未通过,服务器将返回 403 Forbidden,而不是我所期望的 401 Unauthorized。这将导致一个大问题,因为如果用户第一次验证失败,除非他们重新启动浏览器,否则不会提示他们再次输入凭据。那么,我做错了什么?

这是我目前所拥有的:

(实际的 ServiceContract 包含一个返回字符串的方法)

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

我已经注意到这个 other, similar question ,但那里发布的答案都没有实际工作。我希望这个问题的定义更完整的版本会引起更好的回答。

最佳答案

试试这个:

public override void Validate(string userName, string password) 
{
if (null == userName || null == password)
throw new ArgumentNullException();
if (userName == "Test" || password == "Password") return;

WebFaultException rejectEx = new WebFaultException(HttpStatusCode.Unauthorized);
rejectEx.Data.Add("HttpStatusCode", rejectEx.StatusCode);
throw rejectEx;
}

据我所知,这是一种未记录的技术,它依赖于 WCF 堆栈如何在内部管理异常。应该有记录在案的方法,但我还没有找到。

关于c# - 为什么我的自托管 WCF 服务返回 403 Forbidden,而不是 401 Unauthorized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com