如何在使用HttpWebRequest和XML post时添加Bearer和Scope



我已经尝试了以下操作,但仍然无法通过身份验证

string requestXml = doc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "application/xml; charset=UTF-8;";
request.ContentLength = bytes.Length;
request.Method = "POST";            
request.Headers.Add("Authorization", $"Bearer {accessToken} scope=myendpoint");

我也试过

request.Headers.Add("scope", "myendpoint");

首先通过一系列HTTP请求/响应获取一个令牌,然后在随后的API调用(新的HTTP请求/应答(中将该令牌用作承载令牌。获取令牌的方式取决于协议。如果协议是oAuth v2,并且(例如(您正在执行客户端凭据授予类型/流,则scope是一个可选的请求参数。请求可能如下所示:

String serviceURL = "https://blah.accesscontrol.windows.net/...";
String body = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope={2}", "<client id>","<client secret>","<scope>");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(serviceURL);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] payload = System.Text.Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = payload.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(payload, 0, payload.Length);
}
System.Net.WebResponse webResponse = webRequest.GetResponse(););
// extract token from response

添加承载令牌:

request.Headers.Add("Authorization", "Bearer " + token); 

最新更新