Search code examples
c#azureoauth-2.0sharepoint-onlineproject-online

Access Project online api on sharepoint online on c#


I have a sharepoint (myAzure.sharepoint.com). Inside I got a site PWA (project online). PWA offert OData Api. The security of that Api required a User member of your AD (not an app).

I want, in c#, to consumme the api outside azure (like localhost). I need to do it without interractive (web promp interraction with the user).


Solution

  • The only way I found was by "password credential".

    string url = $"https://login.microsoftonline.com/{myTenantId}/oauth2/v2.0/token";
    var formData = new NameValueCollection();
    formData.Add("client_id", clientId);
    formData.Add("client_secret", clientSecret);
    formData.Add("username", username);
    formData.Add("password", password);
    formData.Add("scope", $"https://{myAzure}.sharepoint.com/.default");
    formData.Add("grant_type", "password");
    string encodedFormData = string.Join("&", Array.ConvertAll(formData.AllKeys, key =>
    string.Format("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(formData[key]))));
    
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    
    byte[] formDataBytes = Encoding.UTF8.GetBytes(encodedFormData);
    request.ContentLength = formDataBytes.Length;
    using (var requestStream = request.GetRequestStream())
    {
        requestStream.Write(formDataBytes, 0, formDataBytes.Length);
    }
    
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            if (responseStream != null)
            {
                using (var reader = new System.IO.StreamReader(responseStream))
                {
                    string responseContent = reader.ReadToEnd();
                    JObject jsonResponse = JObject.Parse(responseContent);
                    string accessToken = (string)jsonResponse["access_token"];
    
                    using (HttpClient client = new HttpClient())
                    {                                
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                        HttpResponseMessage response2 = await client.GetAsync($"https://{myAzure}.sharepoint.com/sites/{myPWASite}/_api/ProjectData/Ressources");
                     
                        if (response2.IsSuccessStatusCode)
                        {
                            string responseBody = await response2.Content.ReadAsStringAsync();
                            Console.WriteLine(responseBody);
                        }
                        else
                        {
                            Console.WriteLine("Erreur: " + response.StatusCode);
                        }
                    }
                }
            }
        }
    }
    

    Explanatory documentation