如何验证对WCF Web服务的外部请求?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何验证对WCF Web服务的外部请求?相关的知识,希望对你有一定的参考价值。

我正在尝试通过在SOAP标头中传递用户凭据来验证对WCF Web服务的外部请求。

using (UsrService client = new UsrService())
{
    client.Credentials = new System.Net.NetworkCredential("User 1", "Password 1");
    client.SomeRemoteMethod();
}

我得到了例外:

未处理的异常:System.Net.WebException:请求失败,并显示错误消息:对象已移动

Unhandled exception: System.Net.WebException: The request failed with the error message:
--
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/NuiLogin.aspx?ReturnUrl=%2f0%2fServiceModel%2fSimp
leCustomService.svc%2fsoap">here</a>.</h2>
</body></html>

--.
   in System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClien
tMessage message, WebResponse response, Stream responseStream, Boolean asyncCall
)
   in System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodNa
me, Object[] parameters)
   in UsrService.SayHello() in c:VS2015ProjectsWCFSharedDLLWCFSharedDLLTestPr
oxyClass.cs:line 44
   in ConsoleApplicationForTesting.Program.Main(String[] args) in c:VS2015Projec
tsConsoleApplicationForTestingConsoleApplicationForTestingProgram.cs:line 1
6

如何验证对WCF Web服务的外部请求?

我非常感谢这些信息。谢谢大家。

答案

以下列方式制作。

通过使用传输协议,我发送用户凭据如下:

public const string authServiceUri = "http://localhost:8080/ServiceModel/AuthService.svc/Login";
public static CookieContainer AuthCookie = new CookieContainer();

public static bool TryLogin(string userName, string userPassword)
{
    var authRequest = HttpWebRequest.Create(authServiceUri) as HttpWebRequest;
    authRequest.Method = "POST";
    authRequest.ContentType = "application/json";
    authRequest.CookieContainer = AuthCookie;

    using (var requesrStream = authRequest.GetRequestStream())
    {
        using (var writer = new StreamWriter(requesrStream))
        {
            writer.Write(@"{
                ""UserName"":""" + userName + @""",
                ""UserPassword"":""" + userPassword + @"""
            }");
        }
    }

    using (var response = (HttpWebResponse)authRequest.GetResponse())
    {
        if (AuthCookie.Count > 0)
        {
            return true;
        }
    }
    return false;
}

然后我按如下方式设置CookieContainer:

client.CookieContainer = AuthCookie;

之后,可以访问Web服务:

static void Main(string[] args)
{
    using (UsrService client = new UsrService())
    {
        if(TryLogin("User 1", "User 1"))
        {
            client.CookieContainer = AuthCookie;
            Console.WriteLine(client.SayHello());
        }
    }
}

以上是关于如何验证对WCF Web服务的外部请求?的主要内容,如果未能解决你的问题,请参考以下文章

WCF 身份验证

如何获取 WCF Web 服务请求的 XML SOAP 请求?

WCF如何传递令牌进行身份验证?

防止对我的 wcf 服务的跨域请求

以编程方式添加终结点标头安全 WCF

如何对 WCF 数据服务进行身份验证?