我正在尝试使用CRM和AAD生成的访问令牌来访问SharePoint网站。借助用户名和密码,我可以访问该网站。我为获得令牌而传递的用户名和密码相同。传递令牌时,我收到401未经授权的错误。
private bool GetCRMToken(CRMSettings crmSettings)
{
bool GetCRMTokenSuccess = false;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://login.microsoftonline.com/" + some tenant id + "/oauth2/token");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string("client_id",ClientId),
new KeyValuePair<string, string>("resource",Resource),
new KeyValuePair<string, string>("username",Username),
new KeyValuePair<string, string>("password",Password),
new KeyValuePair<string, string>("Client_Secret",ClientSecret),
new KeyValuePair<string, string>("grant_type","password")
});
var response = client.PostAsync(client.BaseAddress, content).Result;
string resultContent = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
GlobalDataStorage.CRMToken = JsonConvert.DeserializeObject<TokenResponseModel>(resultContent);
GetCRMTokenSuccess = true;
}
}
else
{
var str = exp.error;
GetCRMTokenSuccess = false;
}
}
return GetCRMTokenSuccess;
}
要访问共享站点,我正在传递令牌,如下所示:
context.ExecutingWebRequest += delegate (object sender, WebRequestEventArgs e)
{
e.WebRequestExecutor.WebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//e.WebRequestExecutor.WebRequest.CookieContainer = cc;
};
在context.executequery上执行后,我得到401异常。