我已尝试以下方法,但身份验证仍然失败
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 请求/响应获取 token ,然后在后续 API 调用(新的 HTTP 请求/响应)中使用该 token 作为承载 token 。您获取 token 的方式取决于协议(protocol)。如果协议(protocol)是 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
添加不记名 token :
request.Headers.Add("Authorization", "Bearer " + token);
关于c# - 使用带有 XML post 的 HttpWebRequest 时如何添加 Bearer 和 Scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792547/