[英]How to discover the URL for my organization in Dynamics 365 CRM (online) using Web Api
I cannot connect Dynamics CRM online to discover organization URL using a Web API.我无法使用 Web API 在线连接 Dynamics CRM 以发现组织 URL。 The sample code from Microsoft is not working.
Microsoft 的示例代码不起作用。
I am developing a console application, and want to connect to CRM-online using Web API(we are not using Organization Service since we would like to move to Web API), In the application, I need to discover all available organizations and then query the data from each organization.我正在开发一个控制台应用程序,并希望使用 Web API 连接到 CRM 在线(我们没有使用组织服务,因为我们想转移到 Web API),在应用程序中,我需要发现所有可用的组织,然后进行查询每个组织的数据。 I am using the example from Microsoft, but it didn't work as expected.
我正在使用 Microsoft 的示例,但它没有按预期工作。 Here is sample code .
这是示例代码。
I followed the Quick Start guide in the Azure AD.我遵循了 Azure AD 中的快速入门指南。 using MSAL.NET.
使用 MSAL.NET。
Active Directory Dotnet Core Daemon 活动目录 Dotnet 核心守护进程
I tried both global discovery URL and data center discovery URL , same fault.我尝试了全局发现 URL 和数据中心发现 URL ,同样的错误。
Here are my code using MASL.NET.这是我使用 MASL.NET 的代码。
static void Main(string[] args)
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create("3f4b24d8-61b4-47df-8efc-1232a72c8817")
.WithClientSecret("of+Ozx_ARRX?ONj+QCzWXf84eTQABA17")
.WithAuthority("https://login.microsoftonline.com/common/oauth2/authorize", false)
//.WithAuthority("https://login.microsoftonline.com/3a984a19-7f55-4ea3-a422-2d8771067f87/oauth2/authorize", false)
.Build();
var authResult = app.AcquireTokenForClient(new String[] { "https://disco.crm5.dynamics.com/.default" }).ExecuteAsync().Result;
//var authResult = app.AcquireTokenForClient(new String[] { "https://globaldisco.crm.dynamics.com/.default" }).ExecuteAsync().Result;
//var authResult = app.AcquireTokenForClient(new String[] { "https://crm525842.crm5.dynamics.com/.default" }).ExecuteAsync().Result;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
client.Timeout = new TimeSpan(0, 2, 0);
client.BaseAddress = new Uri("https://disco.crm5.dynamics.com/");
//client.BaseAddress = new Uri("https://crm525842.api.crm5.dynamics.com");
HttpResponseMessage response = client.GetAsync("api/discovery/v9.1/Instances()", HttpCompletionOption.ResponseHeadersRead).Result;
//HttpResponseMessage response = client.GetAsync("api/data/v9.1/WhoAmI()", HttpCompletionOption.ResponseHeadersRead).Result;
if (response.IsSuccessStatusCode)
{
//Get the response content.
string result = response.Content.ReadAsStringAsync().Result;
}
else
{
//401 occurred
throw new Exception(response.ReasonPhrase);
}
}
I can get the access token, I expect this work but the response is:我可以获得访问令牌,我希望这项工作能够正常工作,但响应是:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-CrmServer: HK2CRMWOSDISW11
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Mon, 05 Aug 2019 05:47:12 GMT
Set-Cookie: crmf5cookie=!DTRY0s4VpQxjLnMqwoaZ9AdJzXkdU6Vfto/+0KmA1KJeDxXIK15WxYQUdDi6BwLXgIrzskdvtk0u7A==;secure; path=/
Server: Microsoft-IIS/8.5
WWW-Authenticate: Bearer error=invalid_token, error_description=Error during token validation!. Ticket id feef1832-8a12-4d3d-a426-099176943f35, authorization_uri=https://login.microsoftonline.com/common/oauth2/authorize, resource_id=https://disco.crm5.dynamics.com/
Content-Length: 1293
Content-Type: text/html
}}
I know this post is old, but I experience this exact issue and it has taken me more than 3 day of reading countless articles, samples and answers to finally get my request to be successful.我知道这篇文章很旧,但我遇到了这个确切的问题,我花了超过 3 天的时间阅读了无数文章、示例和答案,最终使我的请求成功。 Here is my code that gets an access code and then uses the token to make a request to gets the contacts from Dynamics CRM.
这是我的代码,它获取访问代码,然后使用令牌发出请求以从 Dynamics CRM 获取联系人。
I believe the main difference betrween my code and the OP's is that I use OAuth v2 as my authority URL.我相信我的代码和 OP 之间的主要区别在于我使用 OAuth v2 作为我的授权 URL。 I am also using PublicClientAppkicationBuilder vs the Confidential version.
我也在使用 PublicClientAppkicationBuilder 与机密版本。 I also set the Tenant to force the login to be within the same organisation.
我还设置租户强制登录在同一组织内。
private static HttpClient _client = new HttpClient
{
BaseAddress = new Uri("https://<your org>.crm11.dynamics.com")
};
public static async Task Main(string[] args)
{
_client.SetClientAuthentication(await Authenticator.GetAccessTokenAsync());
var whoami = await _client.GetJsonAsync("api/data/v9.1/WhoAmI");
Console.WriteLine(whoami);
var contacts = await _client.GetJsonAsync("api/data/v9.1/contacts?$select=fullname");
Console.WriteLine(contacts);
}
public static void SetClientAuthentication(this HttpClient client, string accessToken)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
public static class Authenticator
{
public static async Task<string> GetAccessTokenAsync()
{
var scopes = new string[] { "https://<your org>.crm11.dynamics.com/.default" };
var app = PublicClientApplicationBuilder.Create("<your client id>")
.WithAuthority("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", false)
.WithTenantId("<your tenant id>")
.WithDefaultRedirectUri()
.Build();
AuthenticationResult result;
try
{
var accounts = await app.GetAccountsAsync();
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}
return result?.AccessToken;
}
}
Required App registration ids必需的应用程序注册 ID
Required API permissions for Dynamics CRM Dynamics CRM 所需的 API 权限
Add HTTP localhost as a Mobile/App redirect URL in the Authentication blade在身份验证边栏选项卡中添加 HTTP 本地主机作为移动/应用程序重定向 URL
Set public client to true in the Manifest在 Manifest 中将公共客户端设置为 true
I found <your org> a couple of ways.我通过多种方式找到了<your org> 。 Both are done from the Dynamics 365 Home Page ( https://home.dynamics.com/ ).
两者都是从 Dynamics 365 主页 ( https://home.dynamics.com/ ) 完成的。
Hovering over an app will display the organisation in the URL将鼠标悬停在应用程序上将在 URL 中显示组织
HTTP Request to /apps will have a response containing your organisation对 /apps 的 HTTP 请求将包含您的组织的响应
NB Your orgnaisation will not always start with "org" but will appear in the URL in the aforementioned places.注意您的组织并不总是以“org”开头,而是会出现在上述位置的 URL 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.