我有一个基本的 ASMX 服务,我正在尝试运行它(我宁愿使用 WCF,但无法让服务器使用它)。它在没有安全设置的情况下运行良好,但是一旦我打开安全性,我就会得到:
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="Secured area"'.
我想要的是一个简约的询问用户名称和密码类型的解决方案。
用智能感知浏览代码并没有想出任何我需要的东西。
This看起来它可能有用,但它似乎是 WCF,所以谁知道呢。
我刚刚意识到我可以将其作为现场演示:
这里是服务:http://smplsite.com/sandbox3/Service1.asmx
用户名是
testapp
密码是testpw
.我需要一个命令行应用程序来调用该服务上的函数。在我添加安全性之前,这条线在运行
Add Web Service Reference
后在一个基本的 VS 项目中工作在那个网址上new ServiceReference1.Service1SoapClient().HelloMom("Bob");
这是我目前的尝试(那行不通)
class Program
{
private static bool customValidation(object s, X509Certificate c, X509Chain ch, SslPolicyErrors e)
{ return true }
static void Main(string[] args)
{
// accept anything
ServicePointManager.ServerCertificateValidationCallback +=
new RemoteCertificateValidationCallback(customValidation);
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
binding.Security.Transport.Realm = "Secured area";
// the generated Web Service Reference class
var client = new ServiceReference1.Service1SoapClient(
binding,
new EndpointAddress("https://smplsite.com/sandbox3/Service1.asmx")
);
client.ClientCredentials.UserName.UserName = "testapp";
client.ClientCredentials.UserName.Password = "testpw";
Console.WriteLine(client.HelloMom("Bob"));
}
}
编辑:顺便说一句,这不是网站或在浏览器中运行,访问代码是 C# 命令行应用程序。此外,身份验证是由我无法控制的另一个 IIS 插件完成的。
编辑2:要清楚;我正在寻找的解决方案纯粹是客户端问题。
编辑 3:访问控制是通过
.haccess
系统类型,我喜欢这种方式。我不希望服务代码进行任何身份验证。
最佳答案
编辑:
如何使用这个:
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
OP 说这行不通,现在我看到在他的情况下不会。
我们做这样的事情:
public class MyWebService : System.Web.Services.WebService
{
public AuthenticationHeader AuthenticationInformation;
public class AuthenticationHeader : SoapHeader
{
public string UserName;
public string Password;
}
[WebMethod( Description = "Sample WebMethod." )]
[SoapHeader( "AuthenticationInformation" )]
public bool MyWebMethod()
{
if ( AuthenticationInformation != null )
{
if ( IsUserAuthenticated( AuthenticationInformation.UserName,
AuthenticationInformation.Password, ref errorMessage ) )
{
// Authenticated, do something
}
else
{
// Failed Authentication, do something
}
}
else
{
// No Authentication, do something
}
}
}
请注意,您提供 IsUserAuthenticated()。
然后客户端这样调用它:
MyWebService svc = new MyWebService();
svc.AuthenticationHeaderValue = new MyWebService.AuthenticationHeader();
svc.AuthenticationHeaderValue.UserName = UserID;
svc.AuthenticationHeaderValue.Password = Password;
bool result = svc.MyWebMethod();
关于.net - ASMX 用户名和密码安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770345/