简体   繁体   English

如何使用 System.Net.Http 从 OAuth 请求访问令牌? 401 错误

[英]How to request an access token from OAuth using System.Net.Http? 401 Error

Context语境

I am developing a simple application that requires to receive List Data from a company Online SharePoint site.我正在开发一个简单的应用程序,需要从公司在线 SharePoint 站点接收列表数据。 In order to make REST requests, I must first retrieve an access token from Microsoft's access control service.为了发出 REST 请求,我必须首先从 Microsoft 的访问控制服务中检索访问令牌。 Despite attempting some tutorials and reading documentation, I am new to REST/HTTP am am failing to do so.尽管尝试了一些教程和阅读文档,但我还是 REST/HTTP 的新手,但我没有这样做。

What have I tried?我尝试了什么?

  • Used SharePoint appregnew.aspx to register my app, and generate "Client ID" and "Client Secret" values.使用 SharePoint appregnew.aspx 注册我的应用程序,并生成“客户端 ID”和“客户端密钥”值。 https://[sitename].sharepoint.com/_layouts/15/appregnew.aspx https://[站点名称].sharepoint.com/_layouts/15/appregnew.aspx
  • Used Sharepoint appinv.aspx to authorize my app with read control and generate a "Tenant ID".使用 Sharepoint appinv.aspx 授权我的应用程序具有读取控制权并生成“租户 ID”。 https://[sitename].sharepoint.com/_layouts/15/appinv.aspx https://[站点名称].sharepoint.com/_layouts/15/appinv.aspx
<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read"/>
</AppPermissionRequests>
  • Used SharePoint AppPrincipals.aspx to verify Tenant ID.使用 SharePoint AppPrincipals.aspx 来验证租户 ID。 https://[sitename].sharepoint.com/_layouts/15/AppPrincipals.aspx https://[站点名称].sharepoint.com/_layouts/15/AppPrincipals.aspx
  • Attempted several methods of formatting the request with the following being the latest:尝试了几种格式化请求的方法,以下是最新的:

Updated更新

// Variables removed for security
class Program
{
    static void Main(string[] args)
    {               
        WebRequest myWebRequest;
        string stGetAccessTokenUrl = "https://accounts.accesscontrol.windows.net/{0}/tokens/OAuth/2";

        string tenantID         = "myTenantID";
        string resourceID       = "00000003-0000-0ff1-ce00-000000000000";
        string stClientID       = "myClientID";
        string stClientSecret   = "myClientSecret";
        string stSiteDomain     = "[myCompany].sharepoint.com";

        // URL Format
        stGetAccessTokenUrl = string.Format(stGetAccessTokenUrl, tenantID);
        myWebRequest = WebRequest.Create(stGetAccessTokenUrl);
        myWebRequest.ContentType = "application/x-www-form-urlencoded";
        myWebRequest.Method = "POST";

        // Add the below body attributes to the request
        var postData = "grant_type=client_credentials";
        postData += "&client_id=" + stClientID + "@" + tenantID;
        postData += "&client_secret=" + stClientSecret;
        postData += "&resource=" + resourceID + "/" + stSiteDomain + "@" + tenantID;
        var data = Encoding.ASCII.GetBytes(postData);

        using (var stream = myWebRequest.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
            
        var response = (HttpWebResponse)myWebRequest.GetResponse();
    }
}

What doesn't work?什么不起作用?

I receive a 401 Unauthorized error despite the app having been assigned permissions.尽管已为应用分配了权限,但我收到 401 Unauthorized 错误。

Any help would be greatly appreciated!任何帮助将不胜感激!

You could refer to this article to get the access token: https://social.technet.microsoft.com/wiki/contents/articles/51982.sharepoint-read-online-list-data-from-c-console-application-using-access-token.aspx您可以参考这篇文章获取访问令牌: https://social.technet.microsoft.com/wiki/contents/articles/51982.sharepoint-read-online-list-data-from-c-console-application-使用访问令牌.aspx

 #region Get Access Token using TenantID and App secret ID & Password
 // URL Format
 //https://accounts.accesscontrol.windows.net/tenant_ID/tokens/OAuth/2 Jump
 
 stGetAccessTokenUrl = string.Format(stGetAccessTokenUrl, tenantID);
 myWebRequest = WebRequest.Create(stGetAccessTokenUrl);
 myWebRequest.ContentType = "application/x-www-form-urlencoded";
 myWebRequest.Method = "POST";
  
   
 // Add the below body attributes to the request
 /*
  *  grant_type  client_credentials  client_credentials
  client_id  ClientID@TenantID 
  client_secret  ClientSecret 
  resource  resource/SiteDomain@TenantID  resourceid/abc.sharepoint.com@tenantID
  */
  
 
 var postData = "grant_type=client_credentials";
 postData += "&client_id=" + stClientID +"@" +tenantID;
 postData += "&client_secret=" + stClientSecret;
 postData += "&resource=" + resourceID + "/" + stSiteDomain + "@" + tenantID;
 var data = Encoding.ASCII.GetBytes(postData);
 
 using (var stream = myWebRequest.GetRequestStream())
 {
  stream.Write(data, 0, data.Length);
 }
 var response = (HttpWebResponse)myWebRequest.GetResponse();
 
 var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
 
 string[] stArrResponse = responseString.Split(',');
  
 //get the access token and expiry time ,etc
  
 foreach(var stValues in stArrResponse)
 {
   
  if(stValues.StartsWith("\"access_token\":"))
  {
  //Console.WriteLine(" Result => " + stValues);
  accessToken = stValues.Substring(16);
  //Console.WriteLine(" Result => " + accessToken);
  accessToken = accessToken.Substring(0,accessToken.Length-2);
  // Console.WriteLine(" Result => " + accessToken);
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM