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

How to add Bearer and Scope when using HttpWebRequest with XML post

我已经尝试了以下但仍然无法验证

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 requests/responses 获取令牌,然后在后续 API 调用(新的 HTTP request/response)中使用此令牌作为不记名令牌。您获取令牌的方式取决于协议。如果协议是 oAuth v2 并且(例如)您正在执行客户端凭据授予 type/flow,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);