Calling the Dynamics Global Discovery Service

With the launch of Dynamics 365 comes a global version of the CRM Discovery Service that can be used to find instances across regions. This is a Web API only service and with this service you will no longer have to prompt users for their region, as the service can return a list of all instances from all regions at once. For developers building CRM applications this is an important service to be aware of as it can greatly improve the user experience of the the application since users no longer will have to indicate their region before querying for a list of instances.

You can read the documentation for the Global Discovery Service on the Microsoft Developer Network (MSDN) – Discover the URL for your organization using the Web API.

One of the key aspects of using the new Global Discovery Service is getting an authorization token for the Dynamics Web API that allows you to properly access this resource. This example will utilize the new Server-to-Server (S2S) authentication that has been made available in Dynamics 365 as well. To learn more and setup S2S authentication you can view the MSDN documentation, Build web applications using Server-to-Server (S2S) authentication.

Firstly you will need to initiate a OpenID challenge to get an authorization code that we can then use to acquire a token to use in Web API calls to Dynamics. You can do this using the OWIN method described in the in Walkthrough: Multi-tenant server-to-server authentication (note this can be followed even if not creating a multi-tenant application) or you can make this challenge manually without using OWIN. We use the authorization code returned to then request a token to a particular resource, like a Dynamics instance or the discovery service it self.

To call the global discovery service you will need to request a token for the resource https://disco.crm.dynamics.com/ not the global discovery service address https://globaldisco.crm.dynamics.com/. Below is an example that utilizes ADAL (Active Directory Authentication Library) to retrieve a token that will allow that request against the desired Azure AD tenant with client credentials (client id + secret), the authorization code, return URI as well as the resource indicated above.

// setup parameters for authentication context
var tenantId = "<guid-of-azure-ad-instance>";
var aadInstance = "https://login.microsoftonline.com";

// define auth context
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($"{aadInstance}{tenantId}");

// setup parameters to get token
var code = "<code-returned-from-OpenID-challenge>";
var credential = new ClientCredential("<ClientId>", "<ClientSecret>");
var uri = "<same-return-URI-from-OpenID-challenge>";
var resource = "https://disco.crm.dynamics.com/";

// request token with parameters
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, resource);

Once you have your token we will now use it in a call to the global discovery service. The token you received back must be included in the request authorization header in the call to the global discovery service Web API endpoint https://globaldisco.crm.dynamics.com/api/discovery/v1.0/Instances.

// setup http client for GET of instances from global discovery service
var discoEndpoint = "https://globaldisco.crm.dynamics.com/api/discovery/v1.0/Instances";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), discoEndpoint);

// send http client request
var response = await httpClient.SendAsync(request);

The first thing we are going to want to do with the response is validate that is was successful.

 // validate status code OK
if (response.StatusCode != HttpStatusCode.OK)
{
    throw new Exception($"Global Discovery Service response status code: {response.StatusCode}");
}

If it was not successful then review the WWW-Authenticate in the response header to check to see if it wants another resource to be specified in the token (it might also be as simple as you missed a trailing slash in the resource). If you do see another resource indicated in the response you will need to re-request a token with the resource specified in the response header then re-make your request to the global discovery service. With the refresh token that is included in the authentication result of the AcquireTokenByAuthorizationCodeAsync you can easily re-request a token for a new resource instead of requiring the authorization code. ADAL will cache all your tokens and you will build up a multi-resource token repository by using this method. Below is an example of using the refresh token to now access the Canadian discovery service after getting the following response with the WWW-Authenticate in the header.

Bearer authorization_uri=https://login.windows.net/common/oauth2/authorize, resource_id=https://disco.crm3.dynamics.com/
var newResource = "https://disco.crm3.dynamics.com/";
var authResultCRM4 = await authContext.AcquireTokenByRefreshTokenAsync(authResult.RefreshToken, credential, newResource);

Note: The tenants I have worked with thus far have all used the North American Discovery Service resource (even tenants started on CRM4 for instance).

Once you have successfully been able to get a response with a HTTP status code of OK using the correct token, the body of the response should be a JSON string that can be converted to an object for you to bind or return to other interfaces. The response JSON content if returning the entire instance object should deserialize into a list of the following DiscoInstanceModel class.

public class DiscoInstanceModel
{
    public Guid Id { get; set; }
    public string UniqueName { get; set; }
    public string UrlName { get; set; }
    public string FriendlyName { get; set; }
    public int State { get; set; }
    public string Version { get; set; }
    public string Url { get; set; }
    public string ApiUrl { get; set; }
    public DateTime LastUpdated { get; set; }
}

You can deserialize the data using Newtonsoft.Json.

// read response content to string
var data = await response.Content.ReadAsStringAsync();

// parse the string to a JObject and deserialize to list of DiscoInstanceModel from the content value
var dataValues = JObject.Parse(data); 
var discoInstances = JsonConvert.DeserializeObject<List<DiscoInstanceModel>>(dataValues["value"].ToString());

The service just like the other Dynamics Web API services provided support for $select, $filter as well as $metadata with the instances entity. So if for instance you wanted to get back only instances of a certain version you could do so with the following filter for all those v8.2.x instances.

https://globaldisco.crm.dynamics.com/api/discovery/v1.0/Instances?$filter=startswith(Version,'8.2.')

A lot of the code provided here is meant as a sample, it will need to be adapted to how you will use this service within your own applications. There are lots of ways of using ADAL to obtain and maintain a token to access the service, so it will require you to implement one that works for individual use cases.

Configure ADXStudio Portals and CRM portals with Azure AD B2C

Azure Active Directory B2C is a new Azure service that is targeted at helping your organization utilize consumer based identities within your sites and applications. This is a guide covering setting up ADXStudio Portals version 7 and CRM portals v8.1 with Azure AD B2C as an identity provider through configuration.  As well discuss some of the additional customizations that can be made to the ADXStudio Portal v7 MasterPortal code base to further enhance the user experience.

A recent update to Azure AD B2C policies has allowed ADXStudio Portals and CRM portals to work with Azure AD B2C via configuration.  To learn more about the technical change please view Azure AD B2C Now Supports ADXStudio Portal v7.

CRM portals v8.x customization is limited and therefore the user experience that the customizations below outline with Azure AD B2C cannot be completely implemented.  CRM portals v8.2 is expected to support Azure AD B2C natively in the Fall release or in a future monthly update.  All configuration based settings mentioned apply for ADXStudio and CRM portals interchangeably.

Note that while you can configure B2C with CRM portals it is completely unsupported and not recommended by Microsoft. The concern is that when support is added to CRM portals if you were previously using B2C that the implementation might not be compatible with your existing users. Therefore it is advised that you do not configure B2C with CRM portal until it is released directly as a feature of the product. The date for this has also moved to unknown, there was discussion on this coming shortly in 8.2, but that has not be committed to. If you wish to implement Azure AD B2C then you should use the latest version of ADXStudio Portals.

The benefit of using Azure AD B2C is moving the authentication of your users to a common secure global service that be consumed be various different application platforms because of its standard based implementation of OpenID Connect. This allows your users to have a single identity with a common user experience across your portfolio of applications. ADXStudio Portals and CRM portals with its implementation of ASP.NET Identity built on the OWIN Framework supports OpenID Connect since version 7.0.0020 with providers like Azure AD B2C.

To get started you will need to create an Azure AD B2C directory which is completely free up to 50,000 authentications per month. Once you have your Azure AD B2C directory you have the ability to enable various social identity providers like Facebook, Google, LinkedIn, Amazon and Microsoft Account for you users to use. You can also enable users without a social identity account to create local users via email address or username. To learn more about creating a directory and setting up social providers via the guide here.

One of the unique functions of Azure AD B2C is that it has the concept of policies. The policies allow you to segment configurations of your identity service, providing flexibility per application, process or however you decide to use policies.  Policies allow you to customize the branding, as to what might be collected during sign up or the claims that are returned to an application. Based on how the ADXStudio Portal and CRM portals function with identity providers through configuration it is best implemented with a “Sign Up and Sign In” policy instead of separate policies for “Sign In” and “Sign Up”.

For the ADXStudio Portal or CRM portals to consume B2C we will need to list it as an application in the B2C settings.

  1. Navigate to Azure AD B2C tenant and then the settings for the directory in the Azure Portal and select Applications, then Add.
  2. Add your application name, enable Web App / Web API, and enter your reply URL (this must be HTTPS and it only needs to be your ADX portal root URL).
  3. Click the Create button.
  4. Once the application is created, select it and you should see an Application ID. Copy this value and save it.

To configure OpenID Connect for ADXStudio Portal or CRM portals we need to map the functionality of the CreateOptionsFromPolicy method in the GitHub sample for .NET Web App Startup.Auth.cs to the portal site settings documented here for ADXStudio Portals and here for CRM portals.

Adding a new identity provider with ADXStudio Portal or CRM portal is must be done via the CRM GUI, outlined below are the necessary site settings for Azure AD B2C.

The settings all follow the format of Authentication/OpenIdConnect/AzureADB2C/[setting_name]. The text AzureADB2C can be replaced with your desired provider name, the label seen on the portal is configured through the caption setting.

Authentication/OpenIdConnect/AzureADB2C/AuthenticationType
The value is the name of your B2C policy for Sign Up and Sign In.
Sample Value: B2C_1_SuSi

Authentication/OpenIdConnect/AzureADB2C/MetadataAddress
You can obtain this value by selecting your policy and copying the metadata endpoint address at the top of the panel.
Sample Value: https://login.microsoftonline.com/adxb2c.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_SuSi

b2c_policy

Authentication/OpenIdConnect/AzureADB2C/Authority
You can obtain this value by navigating to your Metadata Address and copying the value of issuer
Sample Value: https://login.microsoftonline.com/52f15a3d-fac9-447f-832b-79e4fc16bff6/v2.0/

b2c_issuer

Authentication/OpenIdConnect/AzureADB2C/ClientId
The value is the Application ID that you saved when setting up the application in the previous steps.
Sample Value: e48b78ef-e274-4480-a3d5-621138ae1b47

Authentication/OpenIdConnect/AzureADB2C/RedirectUri
This value applies to both RedirectUri and PostLogoutRedirectUri. It should be the root URL to your ADX portal.
Sample Value: https://b2cadx.local.adoxio.com

Authentication/OpenIdConnect/AzureADB2C/PostLogoutRedirectUri
This value applies to both RedirectUri and PostLogoutRedirectUri. It should be the root URL to your ADX portal.
Sample Value: https://b2cadx.local.adoxio.com

Authentication/OpenIdConnect/AzureADB2C/Scope
Value: openid

Authentication/OpenIdConnect/AzureADB2C/ResponseType
Value: id_token

Authentication/OpenIdConnect/AzureADB2C/NameClaimType
Value: name

Authentication/OpenIdConnect/AzureADB2C/Caption Optional
This can be set to whatever you would like the button text to read on the Sign In and Register pages of the portal. This value is optional.
Sample Value: Azure AD B2C

Once you have completed all the site settings outlined above associated to your ADX portal website then you should be able to restart the portal application and see the new provider listed under external account.

ADXStudio Portals Sign In:
adx_signin

CRM portals Sign In:
crmportal_signin

You can now test your registration and sign in flows. The nice thing about the Sign Up and Sign In policy and the portal is it will handle that detection as part of its out of the box configuration. All of the other ADXStudio Portals or CRM portal authentication settings can be used and applied to the site as normal.

The following customizations only applies to ADXStudio Portals.

With the out of box code in ADXStudio Portals login controller the logoff or sign out function will only sign you out from the ADX Portal. To modify this functionality you just need to update the Logoff HTTP GET and POST methods in LoginController.cs. This controller can be found in the MasterPortal code base Areas\Account\Controllers folder.

// GET: /Login/LogOff
[HttpGet]
public ActionResult LogOff(string returnUrl)
{
	if (HttpContext.Request.Url != null && !returnUrl.Contains(HttpContext.Request.Url.Authority))
	{
		returnUrl = $"{HttpContext.Request.Url.Scheme}://{HttpContext.Request.Url.Authority}{returnUrl}";
	}

	var authTypes = AuthenticationManager.GetAuthenticationTypes();

	AuthenticationManager.SignOut(new AuthenticationProperties { RedirectUri = returnUrl }, authTypes.Select(t => t.AuthenticationType).ToArray());
	return Redirect(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : "~/");
}

The changes here are to ensure that the return URL passed to Azure B2C is a includes the full site URL and not just the relative path. Azure B2C checks this return URL against what was configured in the application settings to ensure it includes the same root URL.   Additional the code to tell ASP.NET Identity OWIN to sign out not only of the portal but also Azure B2C is to modify the SignOut method of the AuthenticationManager to include the authentication types as a parameter. This causes OWIN to process not only the ADX applicaiton cookie but call the associated Azure B2C logoff method which will remove the Azure B2C cookie as well.

Note – you may also modify the ReturnUrl methods in Helpers\UrlHelper.cs to output a full qualified URL as the return URL instead of modifying the URL in the LogOff HTTP GET method.

The following is the change to the HTTP POST method, no return URL is needed, just the Authentication Types added to the SignOut parameters.

// POST: /Login/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
	var authTypes = AuthenticationManager.GetAuthenticationTypes();

	AuthenticationManager.SignOut(authTypes.Select(t => t.AuthenticationType).ToArray());
	return Redirect("~/");
}

The other changes you would be able to make in the code is mapping claims to CRM properties so that the profile is auto populated. Though you may need to consider a more complex implementation so that all CRM modifications of certain attributes are sync’d back to the Azure AD B2C attribute store. If you are interested then check out the Graph API documentation. For a less complex implementation that does not require complex attribute mapping, you could leave contact profile data collection just to CRM/portal and not collect any additional claims on the Azure B2C side.

If you want to at least ensure the email from Azure B2C is mapped to the CRM Contact email address then you can modify the ExternalLoginCallback method in the LoginController.cs and add lines 8 – 11 highlighted in the following code:

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if (loginInfo == null)
{
	return RedirectToAction("Login");
}

if (string.IsNullOrEmpty(loginInfo.Email))
{
	loginInfo.Email = loginInfo.ExternalIdentity.Claims.FirstOrDefault(a => a.Type == "emails")?.Value;
}

This is necessary due to the AuthenticationManager.GetExternalLoginInfoAsync() method only looking for http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress as the claim type name it would get for email.  Note B2C has been modifying the email claim name recently so you may need to update the Type condition to match what is current.

A last tip, if you plan to only use Azure B2C then it might make sense for your users to skip the portal sign in page and go directly to Azure B2C. This can be done using an out of box site setting Authentication/Registration/LoginButtonAuthenticationType. Simply set this site setting to same value as the site setting Authentication/OpenIdConnect/AzureADB2C/AuthenticationType and the sign in button in headers that utilize the UrlHelper method (default out of box non-liquid based) will forward directly to Azure B2C.