private async Task <AuthenticationResult> GetToken() { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync(new Uri(Configuration["CRMConnection:ServiceUrl"])).Result; string authorityUrl = ap.Authority.Remove(ap.Authority.IndexOf("/oauth2/authorize")); AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authorityUrl, false); CRMOrgURL = ap.Resource; try { return(await GetAccessToken(authorityUrl, CRMOrgURL, Configuration["CRMConnection:ClientID"], Configuration["CRMConnection:ClientSecret"])); } catch (AdalException e) { throw e; } } catch (Exception ex) { throw ex; } }
/// <summary> /// This is to establish the connection to CRM /// </summary> private void CreateCRMConnection() { try { string clientId = ConfigurationManager.AppSettings["CLENT_ID"]; string clientSecret = ConfigurationManager.AppSettings["CLIENT_SECRET"]; ClientCredential credentials = new ClientCredential(clientId, clientSecret); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string domain = ConfigurationManager.AppSettings["DOMAIN"]; string url = $"https://{domain}.api.crm.dynamics.com"; OrganizationServiceContext xrmContext; OrganizationWebProxyClient webProxyClient; AuthenticationParameters authParam = AuthenticationParameters.CreateFromUrlAsync(new Uri(url + "/api/data/")).Result;// CreateFromResourceUrlAsync(new Uri(url + "/api/data/")).Result; var authority = authParam.Authority.Replace(@"oauth2/authorize", ""); AuthenticationContext authContext = new AuthenticationContext(authority, false); AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(url, credentials).Result; webProxyClient = new OrganizationWebProxyClient(new Uri(url + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2"), false); //TODO:Change version to 9.2 webProxyClient.HeaderToken = authenticationResult.AccessToken; this.organizationService = (IOrganizationService)webProxyClient; //new OrganizationServiceProxy(new Uri(serviceUrl), null, credentials, null); Guid orgId = ((WhoAmIResponse)this.organizationService.Execute(new WhoAmIRequest())).OrganizationId; Console.WriteLine("User Login Success"); } catch (Exception ex) { throw new WebException(ex.Message); } }
/// <summary> /// Get the Authority and Support data from the requesting system using a sync call. /// </summary> /// <param name="targetServiceUrl"></param> /// <returns>Populated AuthenticationParameters or null</returns> private static AuthenticationParameters GetAuthorityFromTargetService(Uri targetServiceUrl) { try { // if using ADAL > 4.x return.. // else remove oauth2/authorize from the authority if (_ADALAsmVersion == null) { // initial setup to get the ADAL version var AdalAsm = System.Reflection.Assembly.GetAssembly(typeof(IPlatformParameters)); if (AdalAsm != null) { _ADALAsmVersion = AdalAsm.GetName().Version; } } var foundAuthority = AuthenticationParameters.CreateFromUrlAsync(targetServiceUrl).Result; if (_ADALAsmVersion != null && _ADALAsmVersion > Version.Parse("4.0.0.0")) { foundAuthority.Authority = foundAuthority.Authority.Replace("oauth2/authorize", ""); } return(foundAuthority); } catch (Exception ex) { // Todo: Add exception handling } return(null); }
/// <summary> /// Discover the authentication authority asynchronously. /// </summary> /// <param name="serviceUrl">The specified endpoint address</param> /// <returns>The URL of the authentication authority on the specified endpoint address, or an empty string /// if the authority cannot be discovered.</returns> public static async Task <string> DiscoverAuthorityAsync(string serviceUrl) { try { AuthenticationParameters ap = await AuthenticationParameters.CreateFromUrlAsync( new Uri(serviceUrl + "api/data/")); return(ap.Authority); } catch (HttpRequestException e) { throw new Exception("An HTTP request exception occurred during authority discovery.", e); } catch (Exception e) { // These exceptions ocurr when the service is not configured for OAuth. // -2147024809 message: Invalid authenticate header format Parameter name: authenticateHeader if (e.HResult == -2146233088 || e.HResult == -2147024809) { return(String.Empty); } else { throw e; } } }
/// <summary> /// Creates authentication parameters from the address of the resource. /// Invoked for ADAL 5+ which changed the method used to retrieve authentication parameters. /// </summary> /// <param name="targetServiceUrl">Resource URL</param> /// <returns>AuthenticationParameters object containing authentication parameters</returns> private static AuthenticationParameters CreateFromUrlAsync(Uri targetServiceUrl) { //var result = (Task<AuthenticationParameters>)typeof(AuthenticationParameters) // .GetMethod("CreateFromUrlAsync").Invoke(null, new[] { targetServiceUrl }); var result = AuthenticationParameters.CreateFromUrlAsync(targetServiceUrl); return(result.Result); }
static async Task TestAuth() { string api = "https://dlcrm.crm.dynamics.com"; AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync(new Uri(api)).Result; var creds = new ClientCredential("id in azure", "secret in azure"); AuthenticationContext authContext = new AuthenticationContext(ap.Authority); var token = authContext.AcquireTokenAsync(ap.Resource, creds).Result.AccessToken; using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await httpClient.GetAsync(api + "/contacts?$top=1"); } }
private async Task <AuthenticationContext> CreateAuthenticationContext(string baseUri, string crmUrl, string aadId) { AuthenticationContext authenticationContext; //如果aadId==null,则需要首先获取认证地址 if (aadId == null) { AuthenticationParameters authenticationParameters = await AuthenticationParameters.CreateFromUrlAsync(new Uri(new Uri(crmUrl), "api/data/")); authenticationContext = new AuthenticationContext(authenticationParameters.Authority.Replace("/oauth2/authorize", string.Empty)); } else { authenticationContext = new AuthenticationContext($"https://{baseUri}/{aadId}"); } return(authenticationContext); }
public static async Task Auth() { // use below lines for old version (3.13.5) of adal library // AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync( // new Uri(API_URL)).Result; //Use below lines for latest version of adal library AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync( new Uri(API_URL)).Result; //for latest version of adal // use below lines for old version (3.13.5) of adal library //AuthenticationContext authContext = new AuthenticationContext(ap.Authority); //Use below lines for latest version of adal library AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/<yourtenantid>"); var clinetCredential = new ClientCredential(CLIENT_ID, CLIENT_SECRET); var token = authContext.AcquireTokenAsync(ap.Resource, clinetCredential).Result.AccessToken; using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await httpClient.GetAsync(API_URL + "/contacts?$top=1"); } }