---
title: "Создание классов AuthenticationUtility"
canonical: https://ontargit.com/kz/sozdanie-klassov-authentication-utility/
date: 2021-04-21 17:54:19
description: "Создание классов AuthenticationUtility для упрощения вызова веб-сервисов D365O, которые всегда требуют аутентификации"
keywords: "AuthenticationUtility"
categories: [ERP]
---

Для упрощения вызова веб-сервисов D365O, которые всегда требуют аутентификации, Microsoft написал два класса, открытый код которых выложен по ссылке **[https://github.com/microsoft/Dynamics-AX-Integration/tree/master/ServiceSamples/AuthenticationUtility.](https://github.com/microsoft/Dynamics-AX-Integration/tree/master/ServiceSamples/AuthenticationUtility)**

Рекомендуется создать проект, который будет содержать эти классы, и использовать ссылку на него в собственных проектах, где необходимо подключение к D365O через одинаковое приложение Azure. К этому проекту нужно добавить ссылку на пакет **Microsoft.IdentityModel.Clients.ActiveDirectory**, как описано в статье **[«Добавление пакета Microsoft.IdentityModel.Clients.ActiveDirectory».](https://ontargit.com/dobavlenie-microsoft-identity-model-clients-activedirectory/)**

Первый из классов представляет собой авторизационную информацию. Эта информация должна быть правильно прописана для работы веб-сервиса. Выглядит этот класс следующим образом:**

**

Copy to Clipboard
Syntax Highlighterusing System;

namespace AuthenticationUtility

{

 public partial class ClientConfiguration

 {

 public static ClientConfiguration Default {get {return ClientConfiguration.OneBox; }}

 public static ClientConfiguration OneBox = new ClientConfiguration()

 {

 // You only need to populate this section if you are logging on via a native app. For Service to Service scenarios in which you e.g. use a service principal you don’t need that.

 UriString = “https://oit-adm-boryseda2b5401719f08ddevaos.cloudax.dynamics.com/”,

 UserName = “*****@ontargit.com”,

 // Insert the correct password here for the actual test.

 Password = “*****”,

 // You need this only if you logon via service principal using a client secret. See: https://docs.microsoft.com/en-us/dynamics365/unified-operations/dev-itpro/data-entities/services-home-page to get more data on how to populate those fields.

 // You can find that under AAD in the azure portal

 ActiveDirectoryResource = “https://oit-adm-boryseda2b5401719f08ddevaos.cloudax.dynamics.com”, // Don’t have a trailing “/”. Note: Some of the sample code handles that issue.

 ActiveDirectoryTenant = “https://login.microsoftonline.com/common”, // Some samples: https://login.windows.net/yourtenant.onmicrosoft.com, https://login.windows.net/microsoft.com

 ActiveDirectoryClientAppId = “********-****-****-****-************”,

 // Insert here the application secret when authenticate with AAD by the application

 ActiveDirectoryClientAppSecret = “”,

 // Change TLS version of HTTP request from the client here

 // Ex: TLSVersion = “1.2”

 // Leave it empty if want to use the default version

 TLSVersion = “”,

 };

 public string TLSVersion {get; set;}

 public string UriString {get; set;}

 public string UserName {get; set;}

 public string Password {get; set;}

 public string ActiveDirectoryResource {get; set;}

 public String ActiveDirectoryTenant {get; set;}

 public String ActiveDirectoryClientAppId {get; set;}

 public string ActiveDirectoryClientAppSecret {get; set;}

 }

}

Жирным шрифтом в коде выделены поля, значения которых нужно подставить самому.

Namespace выбираем такой же как и у остального проекта, к которому добавляется данный класс.

Значениями UriString и ActiveDirectoryResource – должен быть URL адрес D365O. URL адрес в переменной ActiveDirectoryResource не должен содержать / в конце.

UserName и Password – это, соответственно, логин и пароль корпоративной учетной записи, имеющей доступ к указанной D365O и указанному далее приложению Azure.

ActiveDirectoryTenant – это адрес URL, по которому происходит авторизация пользователя. Можно написать адрес входа для конкретной компании, а можно оставить как в примере (общий для всех компаний адрес).

ActiveDirectoryClientAppId – Application ID приложения Azure, имеющее доступ к необходимым ресурсам D365O для работы веб-сервиса.

ActiveDirectoryClientAppSecret – ключ приложения Azure, по которому можно подключиться к нему без ввода логина и пароля пользователя. В данном руководстве не рассмотрен.

Второй класс от Microsoft отвечает за логику авторизации на основе введенных в предыдущем классе авторизационных данных. Выглядит он следующим образом:

Copy to Clipboard
Syntax Highlighterusing Microsoft.IdentityModel.Clients.ActiveDirectory;

using System;

namespace AuthenticationUtility

{

 public class OAuthHelper

 {

 /// 

 /// The header to use for OAuth authentication.

 /// 
 public const string OAuthHeader = “Authorization”;

 /// 

 /// Retrieves an authentication header from the service.

 /// 
 /// The authentication header for the Web API call.

 public static string GetAuthenticationHeader(bool useWebAppAuthentication = false)

 {

 string aadTenant = ClientConfiguration.Default.ActiveDirectoryTenant;

 string aadClientAppId = ClientConfiguration.Default.ActiveDirectoryClientAppId;

 string aadClientAppSecret = ClientConfiguration.Default.ActiveDirectoryClientAppSecret;

 string aadResource = ClientConfiguration.Default.ActiveDirectoryResource;

 AuthenticationContext authenticationContext = new AuthenticationContext(

 aadTenant,

 false);

 AuthenticationResult authenticationResult;

 if (useWebAppAuthentication)

 {

 if (string.IsNullOrEmpty(aadClientAppSecret))

 {

 throw new Exception(“Failed OAuth by empty application secret.”);

 }

 try

 {

 // OAuth through application by application id and application secret.

 var creadential = new ClientCredential(

 aadClientAppId,

 aadClientAppSecret);

 authenticationResult = authenticationContext.AcquireTokenAsync(

 aadResource,

 creadential).Result;

 }

 catch (Exception ex)

 {

 throw new Exception(

 string.Format(

 “Failed to authenticate with AAD by application with exception ‘{0}’ and the stack trace ‘{1}'”,

 ex.ToString(),

 ex.StackTrace));

 }

 }

 else

 {

 // OAuth through username and password.

 string username = ClientConfiguration.Default.UserName;

 string password = ClientConfiguration.Default.Password;

 if (string.IsNullOrEmpty(password))

 {

 throw new Exception(“Failed OAuth by empty password.”);

 }

 try

 {

 // Get token object

 var userCredential = new UserPasswordCredential(

 username,

 password);

 authenticationResult = authenticationContext.AcquireTokenAsync(

 aadResource,

 aadClientAppId,

 userCredential).Result;

 }

 catch (Exception ex)

 {

 throw new Exception(

 string.Format(

 “Failed to authenticate with AAD by the credential with exception ‘{0}’ and the stack trace ‘{1}'”,

 ex.ToString(),

 ex.StackTrace));

 }

 }

 // Create and get JWT token

 return authenticationResult.CreateAuthorizationHeader();

 }

 }

}

В коде жирным шрифтом выделена строка namespace. Нужно прописать там namespace, используемый в нашем проекте. В остальном класс остается таким же. Он содержит в себе название токена авторизации (статически прописанное значение “Authorization”), а также метод для получения значения этого токена. В дальнейшем этот токен будет использован при установке соединения с D365O.

__

# Подготовил статью:

ДыкухаБорис Александрович

Senior Software Developer, OntargIT

[](https://www.linkedin.com/in/borys-dykukha-59a7a2a9)