Skip to content

Instantly share code, notes, and snippets.

@Rast1234
Last active October 10, 2018 17:42
Show Gist options
  • Save Rast1234/e75aee58163ff73bd9e95d3415e8e87a to your computer and use it in GitHub Desktop.
Save Rast1234/e75aee58163ff73bd9e95d3415e8e87a to your computer and use it in GitHub Desktop.
IOrganizationService with ADFS IFD authentication and SecurityToken self-renewal
using System;
using log4net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
/// <summary>
/// Only works if ClientCredentials are set (see base.AuthenticateCore)
/// </summary>
public class PersistentOrganizationServiceProxy : OrganizationServiceProxy
{
private readonly ILog log;
public PersistentOrganizationServiceProxy(IServiceManagement<IOrganizationService> serviceManagement, AuthenticationCredentials authenticationCredentials, ILog log) : base(serviceManagement, authenticationCredentials.ClientCredentials)
{
this.log = log;
this.SecurityTokenResponse = authenticationCredentials.SecurityTokenResponse;
}
/// <summary>
/// Has no effect if SecurityTokenResponse is not used by authentication type
/// </summary>
protected override void ValidateAuthentication()
{
if (SecurityTokenResponse != null)
{
if (SecurityTokenResponse.Response.Lifetime.Expires <= DateTime.UtcNow.AddMinutes(15))
{
log.Debug($"SecurityToken needs renewal: expires at [{SecurityTokenResponse.Response.Lifetime.Expires:O}]");
Authenticate();
log.Debug($"SecurityToken new expiration at [{SecurityTokenResponse.Response.Lifetime.Expires:O}]");
}
}
base.ValidateAuthentication();
}
public static IOrganizationService Create(string crmSslUrl, string adfsUrl, Guid userId, ILog log)
{
// crmSslUrl should be like https://crm.blah.blah/orgName/XRMServices/2011/Organization.svc
// adfsUrl should be like https://blah.blah/adfs/services/trust/mex
var uri = new Uri(crmSslUrl);
var appliesTo = $"{uri.Scheme}://{uri.Authority}:{uri.Port}/";
log.Debug($"SslCrmConnector appliesTo [{appliesTo}]");
var orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(uri);
var initialCredentials = orgServiceManagement.Authenticate(new AuthenticationCredentials
{
AppliesTo = new Uri(appliesTo),
HomeRealm = new Uri(adfsUrl)
});
log.Debug($"SslCrmConnector initialCredentials [{initialCredentials}]");
var result = new PersistentOrganizationServiceProxy(orgServiceManagement, initialCredentials, log)
{
CallerId = userId
};
result.EnableProxyTypes();
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment