问题描述
我需要通过基于SharePoint 2010的网站进行身份验证,以便对该网站进行后续的经过身份验证的Web服务调用。我该如何实现?
解决方法
您可以使用如下所示的SharePoint SOAP服务向SharePoint 2010网站进行身份验证:
public Cookie GetSharePoint2010AuthenticationCookie(string url,string userName,string password,string proxyIp)
{
var content = new StringContent(
$@"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body>
<Login xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
<username>{userName}</username>
<password>{password}</password>
</Login>
</soap:Body>
</soap:Envelope>",Encoding.UTF8,"text/xml");
var cookieContainer = new CookieContainer(1);
var clientHandler = new HttpClientHandler {
CookieContainer = cookieContainer
};
var client = new HttpClient(clientHandler)
{
Timeout = new TimeSpan(0,1,0)
};
var siteUri = new Uri(url);
if (!string.IsNullOrWhiteSpace(proxyIp))
{
// In case we are using a proxy IP
// (we are calling a specific machine at a specific IP).
client.BaseAddress =
new Uri($"https://{proxyIp}:443");
client.DefaultRequestHeaders.Add("Host",siteUri.Host);
client.AllowAutoRedirect true;
}
else
{
client.BaseAddress = siteUri;
}
// Make the request.
var result = client.PostAsync("/_vti_bin/authentication.asmx",content)
.GetAwaiter()
.GetResult();
var cookie = cookieContainer.GetCookies(client.BaseAddress)
.FirstOrDefault();
if (result.StatusCode != HttpStatusCode.OK
|| cookie == null)
{
throw new ApplicationException("Failed to generate cookie");
}
return cookie;
}