Authorize WebApp to ADFS in order to access Dynamics CRM Web API

前端 未结 1 1586
小蘑菇
小蘑菇 2021-02-05 14:47

I have a web application that needs to speak with Dynamics CRM 365 Web API. The Dynamics CRM is configured as a Relying Party on ADFS. The server is Windows Server 2016 and ever

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 15:19

    At the end i had to use a system user and send it's credentials in my oAUth request using the code below in order to acquire a valid token:

    namespace TestApp.App_Start {
    public class CrmWebApiClient
    {
        private HttpClient _httpClient;
    
        public CrmWebApiClient()
        {       
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("https://crmUrl");
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _httpClient.DefaultRequestHeaders.Add("OData-MaxVersion","4.0");
            _httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
        }
    
        internal async Task Initilize()
        {
            try
            {
    
                var tokenClient = new HttpClient();             
                var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair("client_id",_clientID),
                    new KeyValuePair("client_secret",_clientSecret),
                    new KeyValuePair("resource",_urlOfResource),
                    new KeyValuePair("username",_usernameOfSystemUser),
                    new KeyValuePair("password",_passwordOfSystemUser),
                    new KeyValuePair("grant_type","password"),
                });
                var res = tokenClient.PostAsync("https://adfsUrl/adfs/oauth2/token", content);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                var accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
    
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesstoken);
    
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Exception when requesting the bearer token from ADFS: {ex.Message} - {ex.InnerException?.Message}");
            }
    
        }
    
        internal async Task GetAccountsAsync()
        {
            var result = string.Empty;
            try
            {
                result = _httpClient.GetStringAsync("/api/data/v8.0/accounts").Result;
    
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Exception when calling the CRM api: {ex.Message} - {ex.InnerException?.Message}");
            }
            return result;
        }
    }
    }
    
    
    // Use the above class like that
    var httpClient = new CrmWebApiClient();
    httpClient.Initilize().Wait();
    var result = httpClient.GetAccountsAsync().Result;
    

    0 讨论(0)
提交回复
热议问题