带认证令牌的Rest Post调用

本文关键字:Post 调用 Rest 认证 令牌 | 更新日期: 2023-09-27 18:15:36

我正试图从我的客户端应用程序(WPF应用程序)发送一个Post请求到SharePoint Online (Claims Based Auth Site)。在这种情况下,应该更新ListItem,将'Title'更改为'Test'。

我正在通过MsOnlineClaimsHelper类检索CookieContainer它成功地返回给我一个验证令牌。

但是当我尝试发送请求时,响应是The remote server returned an error: (403) Forbidden.

<<p> WebRequest代码/strong>
try
{
    var claimshelper = new MsOnlineClaimsHelper(baseUrl, _userName, _password);
    var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/" + url);
    request.CookieContainer = claimshelper.CookieContainer;
    request.Method = "POST";
    request.Headers.Add("X-HTTP-Method", "MERGE");
    request.Headers.Add("If-Match", "*");
    request.Accept = "application/json;odata=verbose";
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(json);
        streamWriter.Flush();
    }
    var webResp = request.GetResponse() as HttpWebResponse;
    var theData = new StreamReader(webResp.GetResponseStream(), true);
    string payload = theData.ReadToEnd();
}
catch (Exception ex)
{

}

Rest Url:

/_api/lists/getbytitle('SampleList')/items(1)

Json载荷:

string json = "{ '__metadata': { 'type': 'SP.Data.SampleListListItem' }, 'Title': 'Test'}";

错误:

The remote server returned an error: (403) Forbidden.

带认证令牌的Rest Post调用

此错误发生的原因是SharePoint 2013 REST服务要求用户在每个create, updatedelete操作中包含Request Digest值。然后SharePoint使用该值来识别非真实请求。

如何提供请求摘要值

MsOnlineClaimsHelper class (MsOnlineClaimsHelper.cs文件)中添加以下方法来请求表单摘要值:

/// <summary>
/// Request Form Digest value
/// </summary>
/// <returns></returns>
private string GetFormDigest()
{
    var endpoint = "/_api/contextinfo";
    var request = (HttpWebRequest) WebRequest.Create(_host.AbsoluteUri + endpoint);
    request.CookieContainer = new CookieContainer();
    request.Method = "POST";
    //request.Accept = "application/json;odata=verbose";
    request.ContentLength = 0;
    using (var response = (HttpWebResponse)request.GetResponse())
    {
         using (var reader = new StreamReader(response.GetResponseStream()))
         {
             var result = reader.ReadToEnd();
             // parse the ContextInfo response
             var resultXml = XDocument.Parse(result);
             // get the form digest value
             var e = from e in resultXml.Descendants()
                                 where e.Name == XName.Get("FormDigestValue", "http://schemas.microsoft.com/ado/2007/08/dataservices")
                            select e;
             _formDigest = e.First().Value;   
         }
    }
    return _formDigest;
}

and FormDigest property:

private string _formDigest;
public string FormDigest
{
    get
    {
       if (_formDigest == null || DateTime.Now > _expires)
       {
           return GetFormDigest();
       }
       return _formDigest;
    }
}

如何使用SharePoint 2013 REST API对ListItem执行更新操作

下面的示例演示如何使用所提供的请求表单摘要

的实现来执行列表项的更新

重点:

  • X-RequestDigest头用于指定表单摘要值
  • 请求Content Type必须指定

的例子:

var userName = "username@contoso.onmicrosoft.com";
var password = "password";
var payload = "{ '__metadata': { 'type': 'SP.Data.TasksListItem' }, 'Title': 'New Tasl'}";  //for a Task Item

try
{
    var claimshelper = new MsOnlineClaimsHelper(baseUrl, _userName, _password);
    var request = (HttpWebRequest)WebRequest.Create(baseUrl + "/" + endpointUrl);
    request.CookieContainer = claimshelper.CookieContainer;
    request.Headers.Add("X-RequestDigest", claimshelper.FormDigest);
    request.Method = "POST";
    request.Headers.Add("X-HTTP-Method", "MERGE");
    request.Headers.Add("If-Match", "*");
    request.Accept = "application/json;odata=verbose";
    request.ContentType = "application/json;odata=verbose";
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(payload);
        writer.Flush();
    }
    var response = request.GetResponse() as HttpWebResponse;
    //...
 }
 catch (Exception ex)
 {
    //Error handling goes here.. 
 }