简体   繁体   English

Sharepoint Rest API 访问令牌的身份验证问题 ZBF50D5E661106D0ABE925AFE3EZEZ7

[英]Sharepoint Rest API Authentication issues with Access Token Header

I'm trying to implement a C# program to connect to Sharepoint API through modern authentication (Client ID\ Client Secret).我正在尝试实现一个 C# 程序以通过现代身份验证(客户端 ID\客户端密码)连接到 Sharepoint API。

I've registered an APP with Sharepoint overall permissions on Azure Active Directory, in order to generate Client Id and Client Secret.我已经在 Azure Active Directory 上注册了一个具有 Sharepoint 总体权限的 APP,以便生成客户端 ID 和客户端密码。

Next steps should be retrieval of the Access Token from the Microsoft login page, and then construction of all following requests using the bearing token I've generated.下一步应该是从 Microsoft 登录页面检索访问令牌,然后使用我生成的承载令牌构建所有后续请求。

Retrieval of the Access Token just works fine.访问令牌的检索工作正常。 The problem is when I try to include the token in the authorization header on the following calls.问题是当我尝试在以下调用中将令牌包含在授权 header 中时。

I always get 401 Unhautorized when building my requests from code.从代码构建我的请求时,我总是得到 401 Unhautorized。 Debugging the response content, what I get is "x-ms-diagnostics: 3000006;reason="Token contains invalid signature"; category"invalid_client" . Instead if I try to replicate the call in Postman I get the following error "{"error_description":"Unsupported security token."}".调试响应内容,我得到的是"x-ms-diagnostics: 3000006;reason="Token contains invalid signature"; category"invalid_client" 。相反,如果我尝试在 Postman 中复制调用,则会收到以下错误“{” error_description":"不支持的安全令牌。"}"。

I provide my code below.我在下面提供我的代码。 Does anybody knows what is going on?有人知道发生了什么吗?

     var b2cAuthUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
    
                var client = new HttpClient();
    
                var dict = new Dictionary<string, string>();
                dict.Add("Content-Type", "application/x-www-form-urlencoded");
                dict.Add("grant_type", "client_credentials");
                dict.Add("client_id", clientId);
                dict.Add("client_secret", clientSecret);
                dict.Add("scope", scope);
    
                // Execute post method
                using (var methodResp = client.PostAsync(b2cAuthUri, new FormUrlEncodedContent(dict)))
                {
    
                    var callResult = methodResp.Result.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(callResult))
                    {
                        //I have my Access Token here :)
                        using (MemoryStream DeSerializememoryStream = new MemoryStream())
                        {
                           
    
                            //initialize DataContractJsonSerializer object and pass custom token class type to it
                            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken));
    
                            //user stream writer to write JSON string data to memory stream
                            StreamWriter writer = new StreamWriter(DeSerializememoryStream);
                            writer.Write(callResult);
                            writer.Flush();
    
                            DeSerializememoryStream.Position = 0;
                            //get the Desrialized data in object of type Student
                            AccessToken SerializedObject = (AccessToken)serializer.ReadObject(DeSerializememoryStream);
                            var tokenBytes = System.Text.Encoding.UTF8.GetBytes(SerializedObject.access_token);
                            //64bit serialized token
                            var tokenBase64 = System.Convert.ToBase64String(tokenBytes);
    
                            //Here I try to make a call with the access token as header
                            var testURI = "https://myorg.sharepoint.com/sites/crmkb/_api/web/lists";
    
                            HttpWebRequest testReq = (HttpWebRequest)HttpWebRequest.Create(testURI);
                            testReq.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + tokenBase64);
                            testReq.Method = "GET";
                            //This fails on 401 code
                            HttpWebResponse response = (HttpWebResponse)testReq.GetResponse();
    
    
                        }
                    }
                }

SharePoint Online has blocked the Azure AD App Client Secret, so if you want to use Azure AD App to authentication with SharePoint Rest API, it's necessary to use Certificate option: SharePoint Online has blocked the Azure AD App Client Secret, so if you want to use Azure AD App to authentication with SharePoint Rest API, it's necessary to use Certificate option:

Calling SharePoint Online APIs using Azure AD App-Only permissions and certificate auth 使用 Azure AD App-Only 权限和证书身份验证调用 SharePoint 在线 API

Another option is to use the SharePoint hosted App Id/ Secret registered in "/_layouts/15/appregnew.aspx", this way supported the Client Secret, please check the demo test in Postman:另一种选择是使用在“/_layouts/15/appregnew.aspx”中注册的 SharePoint 托管的 App Id/ Secret,这种方式支持 Client Secret,请查看 Postman 中的演示测试:

Accessing SharePoint Data using Postman (SharePoint REST API) 使用 Postman(SharePoint REST API)访问 SharePoint 数据

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

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