2017-07-17 3 views
0

Probablement un doublon, mais comme je n'ai pas trouvé de réponse exacte, je poste ceci.Dynamics CRM - Impossible de s'authentifier auprès de l'API Web pour consommer des données?

J'ai des informations d'identification pour la dynamique CRM Web api & Je les utiliser dans mon code comme suit:

string username = @"[email protected]"; 
    string password = @"XXXXXXXX"; 
    string domain = @"tmeictest.crm8.dynamics.com"; 
    string apiURL = @"https://tmeictest.api.crm8.dynamics.com/api/data/v8.2/"; 

Ensuite, je suis initialisant le client en utilisant la méthode comme suit:

HttpClient client = GetNewHttpClient(username, password, domain, apiURL); 

public HttpClient GetNewHttpClient(string userName, string password, string domainName, string webAPIBaseAddress) 
    { 
     HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(userName, password, domainName) }); 
     client.BaseAddress = new Uri(webAPIBaseAddress); 
     client.Timeout = new TimeSpan(0, 2, 0); 
     return client; 
    } 

J'appelle la réponse

HttpResponseMessage msg = client.GetAsync(apiURL).Result; 

Mais il donne

statut non autorisé 401.

j'ai vérifié dans le navigateur directement & je suis capable de se connecter. Mais quand je l'utilise dans mon code, il ne s'authentifie pas.

Est-ce que quelque chose me manque ici?

Répondre

0

Voici un exemple de ce MSDN article contenant beaucoup d'exemples de code WebAPI pour C#:

/// <summary> 
    /// Obtains the connection information from the application's configuration file, then 
    /// uses this info to connect to the specified CRM service. 
    /// </summary> 
    /// <param name="args"> Command line arguments. The first specifies the name of the 
    /// connection string setting. </param> 
    private void ConnectToCRM(String[] cmdargs) 
    { 
    //Create a helper object to read app.config for service URL and application 
    // registration settings. 
    Configuration config = null; 
    if (cmdargs.Length > 0) 
    { config = new FileConfiguration(cmdargs[0]); } 
    else 
    { config = new FileConfiguration(null); } 
    //Create a helper object to authenticate the user with this connection info. 
    Authentication auth = new Authentication(config); 
    //Next use a HttpClient object to connect to specified CRM Web service. 
    httpClient = new HttpClient(auth.ClientHandler, true); 
    //Define the Web API base address, the max period of execute time, the 
    // default OData version, and the default response payload format. 
    httpClient.BaseAddress = new Uri(config.ServiceUrl + "api/data/"); 
    httpClient.Timeout = new TimeSpan(0, 2, 0); 
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); 
    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0"); 
    httpClient.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/json")); 
    } 
1

Le code de la question ne fonctionnerait que pour CRMs On-Premise. Je n'ai pas testé la solution ci-dessous, mais vous pouvez essayer. L'identifiant client ci-dessous sera celui que vous recevrez lors de l'enregistrement de votre CRM avec AAD. Étapes here.

var client = new HttpClient(); 

var authenticationContext = new AuthenticationContext(
    authenticationParameters.Authority, false); 

AuthenticationParameters authenticationParameters = 
    AuthenticationParameters.CreateFromResourceUrlAsync(
     "https://tmeictest.api.crm8.dynamics.com").Result; 

var userCredential = new UserCredential(@"[email protected]", @"XXXXXXXX"); 

AuthenticationResult authenticationResult = 
    authenticationContext.AcquireToken(
     authenticationParameters.Resource, @"" /* clientId */, userCredential); 

client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); 

HttpResponseMessage msg = client.GetAsync(apiURL).Result;