public void GetAuthenticationCredentials( [Frozen] Mock <IHttpClient> httpClientMock, [Greedy] UsersComponent sut, int contextId, int userId, AuthenticationCredentials authenticationCredentials) { // ARRANGE var json = JObject.FromObject(authenticationCredentials); httpClientMock.SetupApiCall(sut, CallType.View, "getAuthenticationCredentials", new Parameters { { "contextId", contextId }, { "userId", userId } }) .Returns(json.ToString()) .Verifiable(); // ACT var result = sut.GetAuthenticationCredentials(contextId, userId); // ASSERT result.ShouldBeEquivalentTo(authenticationCredentials); httpClientMock.Verify(); }
private static void PlainSdk() { try { Console.WriteLine("Testing plain sdk"); var defaultCredentials = new AuthenticationCredentials() { ClientCredentials = new ClientCredentials() { Windows = { ClientCredential = CredentialCache.DefaultNetworkCredentials } } }; IServiceManagement <IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(serviceUri); // go crazy on creating new proxies to simulate, for example, a high traffic web api. Parallel.ForEach(Enumerable.Range(0, 100000), (index) => { var proxy = new OrganizationServiceProxy(orgServiceManagement, defaultCredentials.ClientCredentials); // From the link above: // If you enable early-bound types on OrganizationServiceProxy through one of the EnableProxyTypes() methods, // you must do the same on all service proxies that are created from the cached IServiceManagement < TService > object. proxy.EnableProxyTypes(); proxy.Execute(new WhoAmIRequest()); }); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType) { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain); break; case AuthenticationProviderType.LiveId: authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice(); break; default: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; //Windows/Kerberos break; } return(authCredentials); }
/// <summary> /// /// </summary> public void Run() { //<snippetAuthenticateWithNoHelp1> IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>( new Uri(_discoveryServiceAddress)); AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; // Set the credentials. AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType); String organizationUri = String.Empty; // Get the discovery service proxy. using (DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials)) { // Obtain organization information from the Discovery service. if (discoveryProxy != null) { // Obtain information about the organizations that the system user belongs to. OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy); // Obtains the Web address (Uri) of the target organization. organizationUri = FindOrganization(_organizationUniqueName, orgs.ToArray()).Endpoints[EndpointType.OrganizationService]; } } //</snippetAuthenticateWithNoHelp1> if (!String.IsNullOrWhiteSpace(organizationUri)) { //<snippetAuthenticateWithNoHelp3> IServiceManagement <IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>( new Uri(organizationUri)); // Set the credentials. AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType); // Get the organization service proxy. using (OrganizationServiceProxy organizationProxy = GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials)) { // This statement is required to enable early-bound type support. organizationProxy.EnableProxyTypes(); // Now make an SDK call with the organization service proxy. // Display information about the logged on user. Guid userid = ((WhoAmIResponse)organizationProxy.Execute( new WhoAmIRequest())).UserId; SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity <SystemUser>(); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); } //</snippetAuthenticateWithNoHelp3> } }
void NetConnectionOnConnect(object sender, EventArgs eventArguments) { /// TODO: Check if there was a problem connecting // Now that we are connected call the remote login function AuthenticationCredentials authenticationCredentials = new AuthenticationCredentials(); authenticationCredentials.authToken = AuthResponse.Token; authenticationCredentials.clientVersion = ConnectionData.Authentication.ClientVersion; authenticationCredentials.domain = ConnectionData.Authentication.Domain; authenticationCredentials.ipAddress = ConnectionData.Authentication.IPAddress; authenticationCredentials.locale = ConnectionData.Authentication.Locale; authenticationCredentials.oldPassword = null; authenticationCredentials.partnerCredentials = null; authenticationCredentials.securityAnswer = null; authenticationCredentials.password = ConnectionData.Password; authenticationCredentials.username = ConnectionData.User; // Add some default headers RPCNetConnection.AddHeader(MessageBase.RequestTimeoutHeader, false, 60); RPCNetConnection.AddHeader(MessageBase.FlexClientIdHeader, false, Guid.NewGuid().ToString()); RPCNetConnection.AddHeader(MessageBase.EndpointHeader, false, EndpointString); RPCNetConnection.Call(EndpointString, "loginService", null, "login", new Responder <Session>(OnLogin, OnLoginFault), authenticationCredentials); }
private void GetOrganizationCollection(object monitorSync, Uri discoveryUri, out OrganizationDetailCollection orgs) { IServiceManagement <IDiscoveryService> serviceManagement; try { serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(discoveryUri); } catch (Exception) { orgs = null; return; } AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType); using (DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials)) { orgs = DiscoverOrganizations(discoveryProxy); } lock (monitorSync) { Monitor.Pulse(monitorSync); } }
public void SetAuthenticationCredentials( [Frozen] Mock <IHttpClient> httpClientMock, [Greedy] UsersComponent sut, int contextId, int userId, AuthenticationCredentials authenticationCredentials) { // ARRANGE var parameters = new Parameters { { "contextId", contextId }, { "userId", userId } }; foreach (var parameter in authenticationCredentials.Parameters) { parameters.Add(parameter.Key, parameter.Value); } httpClientMock.SetupApiCall(sut, CallType.Action, "setAuthenticationCredentials", parameters) .ReturnsOkResult() .Verifiable(); // ACT sut.SetAuthenticationCredentials(contextId, userId, authenticationCredentials); // ASSERT httpClientMock.Verify(); }
/// <summary> /// /// </summary> public OrganizationServiceProxy GetOrganizationProxy() { IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(new Uri(DiscoveryServiceAddress)); AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType); String organizationUri = String.Empty; // Get the discovery service proxy. using (DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials)) { // Obtain organization information from the Discovery service. if (discoveryProxy != null) { // Obtain information about the organizations that the system user belongs to. OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy); // Obtains the Web address (Uri) of the target organization. organizationUri = FindOrganization(OrganizationUniqueName, orgs.ToArray()).Endpoints[EndpointType.OrganizationService]; } } IServiceManagement <IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(organizationUri)); // Set the credentials. AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType); // Get the organization service proxy. return(GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials)); }
//<snippetAuthenticateWithNoHelp2> /// <summary> /// Obtain the AuthenticationCredentials based on AuthenticationProviderType. /// </summary> /// <param name="service">A service management object.</param> /// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param> /// <returns>Get filled credentials.</returns> private AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType) { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain); break; case AuthenticationProviderType.LiveId: throw new Exception("LiveId is no longer used."); default: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; // Windows Kerberos break; } return(authCredentials); }
public static OrganizationServiceProxy getProxy() { IServiceManagement <IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(OrganizationUri)); AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; if (endpointType == AuthenticationProviderType.LiveId) { var connectionString = getConnectionString(); var connection = CrmConnection.Parse(connectionString); OrganizationService servicio = new OrganizationService(connection); IOrganizationService _service = (IOrganizationService)servicio.InnerService; OrganizationServiceProxy _proxy = (OrganizationServiceProxy)_service; return(_proxy); } else if (endpointType == AuthenticationProviderType.ActiveDirectory) { ClientCredentials credentials = new ClientCredentials(); credentials.Windows.ClientCredential = new System.Net.NetworkCredential(UserName, Password, dominio); OrganizationServiceProxy _proxy = new OrganizationServiceProxy(new Uri(OrganizationUri), null, credentials, null); return(_proxy); } else //esta será la que realmente se utilice en el caso del nuevo Crm online { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials.UserName.UserName = UserName; authCredentials.ClientCredentials.UserName.Password = Password; OrganizationServiceProxy _proxy = GetProxy <IOrganizationService, OrganizationServiceProxy>(serviceManagement, authCredentials); return(_proxy); } }
private void editCredentialToolStripMenuItem_Click(object sender, EventArgs e) { if (listViewCredentials.SelectedItems.Count > 0) { KeyValuePair <SecurityPrincipal, ICredentialObject> pair = (KeyValuePair <SecurityPrincipal, ICredentialObject>)listViewCredentials.SelectedItems[0].Tag; using (CredentialEditorForm frm = new CredentialEditorForm((p) => !p.Equals(pair.Key) && CheckPrincipal(p))) { frm.Principal = pair.Key; AuthenticationCredentials c = pair.Value as AuthenticationCredentials; frm.Username = c.Username; frm.Password = c.Password; frm.Domain = c.Domain; if (frm.ShowDialog(this) == DialogResult.OK) { SecurityPrincipal p = frm.Principal; AuthenticationCredentials creds = new AuthenticationCredentials(frm.Username, frm.Domain, frm.Password); _credentials[p] = creds; UpdateCredentials(); OnCredentialsUpdated(); } } } }
private void AddCredential(SecurityPrincipal principal, AuthenticationCredentials creds) { ListViewItem item = new ListViewItem(String.Format("{0}@{1}", principal.Name, principal.Realm)); item.SubItems.Add(creds.Username); item.SubItems.Add(creds.Domain); }
/// <summary> /// Obtain the AuthenticationCredentials based on AuthenticationProviderType. /// </summary> /// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param> /// <returns>Get filled credentials.</returns> private AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType) { var authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new NetworkCredential(CrmConfig.Username, CrmConfig.Password, CrmConfig.Domain); break; case AuthenticationProviderType.LiveId: authCredentials.ClientCredentials.UserName.UserName = CrmConfig.Username; authCredentials.ClientCredentials.UserName.Password = CrmConfig.Password; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); break; case AuthenticationProviderType.None: authCredentials.ClientCredentials = new ClientCredentials(); authCredentials.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; break; default: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = CrmConfig.Username; authCredentials.ClientCredentials.UserName.Password = CrmConfig.Password; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; //Windows/Kerberos break; } return authCredentials; }
/// <summary> /// Generic method to obtain discovery/organization service proxy instance. /// </summary> /// <typeparam name="TService"> /// Set IDiscoveryService or IOrganizationService type to request respective service proxy instance. /// </typeparam> /// <typeparam name="TProxy"> /// Set the return type to either DiscoveryServiceProxy or OrganizationServiceProxy type based on TService type. /// </typeparam> /// <param name="serviceManagement">An instance of IServiceManagement</param> /// <param name="authCredentials">The user's Microsoft Dynamics CRM logon credentials.</param> /// <returns></returns> private TProxy GetProxy <TService, TProxy>(IServiceManagement <TService> serviceManagement, AuthenticationCredentials authCredentials) where TService : class where TProxy : ServiceProxy <TService> { var classType = typeof(TProxy); if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory) { var tokenCredentials = serviceManagement.Authenticate(authCredentials); // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse. if (tokenCredentials.SecurityTokenResponse == null) { throw new NullReferenceException("There was an error creating the service connection as the SecurityTokenResponse is null. Check you have the correct authentication type and connection details"); } return((TProxy)classType .GetConstructor(new[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) }) .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse })); } // Obtain discovery/organization service proxy for ActiveDirectory environment. // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials. return((TProxy)classType .GetConstructor(new[] { typeof(IServiceManagement <TService>), typeof(ClientCredentials) }) .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials })); }
static AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType) { string _userName = ConfigurationManager.AppSettings["CRMUser"]; string _password = ConfigurationManager.AppSettings["CRMPWD"]; String _domain = ConfigurationManager.AppSettings["Domain"]; AuthenticationCredentials authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain); break; default: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; // Windows Kerberos break; } return(authCredentials); }
//_userId = new Guid("870BEBB1-8C42-E611-80EA-5065F38BF4F1"); public static IOrganizationService ConnectToMSCRM() { try { var discoveryUri = ConfigurationManager.AppSettings["DiscoveryUri"]; IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>( new Uri(discoveryUri)); AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; // Set the credentials. AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType); Uri serviceUri = new Uri(ConfigurationSettings.AppSettings["OrganizationUri"]); OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, authCredentials.ClientCredentials, null); proxy.EnableProxyTypes(); IOrganizationService service = (IOrganizationService)proxy; return(service); } catch (Exception ex) { MessageBox.Show("Error while connecting to CRM " + ex.Message, "CRM connection", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
public IOrganizationService GetOrgService(string orgname) { try { var customerCredentials = new CustomerCredentialsHandler().GetCredentials(orgname); var discoveryUri = customerCredentials.discoveryurl; //ConfigurationManager.AppSettings["DiscoveryUri"]; IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>( new Uri(discoveryUri)); AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; // Set the credentials. AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType, customerCredentials); Uri serviceUri = new Uri(customerCredentials.orgurl); //ConfigurationSettings.AppSettings["OrganizationUri"]); OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, authCredentials.ClientCredentials, null); proxy.EnableProxyTypes(); IOrganizationService service = (IOrganizationService)proxy; return(service); } catch (SoapException ex) { throw new Exception(ex.Message); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// Generic method to obtain discovery/organization service proxy instance. /// </summary> /// <typeparam name="TService"> /// Set IDiscoveryService or IOrganizationService type to request respective service proxy instance. /// </typeparam> /// <typeparam name="TProxy"> /// Set the return type to either DiscoveryServiceProxy or OrganizationServiceProxy type based on TService type. /// </typeparam> /// <param name="serviceManagement">An instance of IServiceManagement</param> /// <param name="authCredentials">The user's Microsoft Dynamics CRM logon credentials.</param> /// <returns></returns> private TProxy GetProxy <TService, TProxy>( IServiceManagement <TService> serviceManagement, AuthenticationCredentials authCredentials) where TService : class where TProxy : ServiceProxy <TService> { Type classType = typeof(TProxy); if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory) { AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials); // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse. return((TProxy)classType .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) }) .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse })); } // Obtain discovery/organization service proxy for ActiveDirectory environment. // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials. return((TProxy)classType .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(ClientCredentials) }) .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials })); }
private void ResolveCredentials(object sender, ResolveCredentialsEventArgs e) { if (InvokeRequired) { Invoke(new EventHandler <ResolveCredentialsEventArgs>(ResolveCredentials), sender, e); } else { if (e.Principal.PrincipalType == typeof(AuthenticationCredentials)) { if (_document.Credentials.ContainsKey(e.Principal)) { e.Result = new ResolveCredentialsResult(_document.Credentials[e.Principal], false); } else { using (GetAuthenticationCredentialsForm frm = new GetAuthenticationCredentialsForm(e.Principal)) { if (frm.ShowDialog(this) == DialogResult.OK) { AuthenticationCredentials creds = new AuthenticationCredentials(frm.Username, frm.Domain, frm.Password); e.Result = new ResolveCredentialsResult(creds, frm.SaveCreds && frm.SessionOnly); if (frm.SaveCreds && !frm.SessionOnly) { _document.Credentials[e.Principal] = creds; credentialsEditorControl.UpdateCredentials(); } } } } } } }
/// <summary> /// SchematronHelper /// </summary> /// <param name="schematronEndpoint">Endpoint Url. Either the test or prod instance</param> /// <param name="credential">NAAS Credentials. Must correspond to the schematronEndpoint environment</param> /// <param name="flowSchemaMap">Collection of Flow to Schema Version mappings</param> /// <param name="proxy">Web Proxy in case we are behind one</param> public SchematronHelper(string schematronEndpoint, AuthenticationCredentials credential, Dictionary <string, string> flowSchemaMap, IWebProxy proxy) { LOG.Debug("Configuring SchematronHelper with: " + schematronEndpoint); LOG.Debug(" credential: " + credential); LOG.Debug(" proxy: " + proxy); if (string.IsNullOrEmpty(schematronEndpoint)) { throw new ArgumentNullException("documentPath"); } if (credential == null) { throw new ArgumentNullException("credential"); } if (flowSchemaMap == null || flowSchemaMap.Count == 0) { throw new ArgumentException("FlowSchemaMap not configured"); } _schematronClient = new Windsor.Node.Schematron.SchematronHelper(); _schematronClient.Configure(schematronEndpoint, credential.UserName, credential.Password, proxy); _flowSchemaMap = flowSchemaMap; }
public RemotingMessageReceivedEventArgs HandleMessage(object sender, RemotingMessageReceivedEventArgs e) { object[] body = e.Body as object[]; AuthenticationCredentials creds = body[0] as AuthenticationCredentials; PoroServer.ClientVersion = creds.ClientVersion; Session session = new Session { Password = creds.Password, Summary = new AccountSummary { AccountId = int.MaxValue - 2, Username = creds.Username, HasBetaAccess = true, IsAdministrator = false, PartnerMode = false, NeedsPasswordReset = false }, Token = "fake" }; e.ReturnRequired = true; e.Data = session; return(e); }
/// <summary> /// Establishes a service configuration at <see cref="Uri"/> location using supplied <see cref="AuthenticationCredentials"/> /// </summary> /// <param name="serviceUri">The service endpoint location</param> /// <param name="credentials">The auth credentials</param> /// <remarks> /// <see cref="AuthenticationCredentials"/> can represent AD, Claims, or Cross-realm Claims <see cref="ClientCredentials"/> /// The authCredentials may already contain a <see cref="SecurityTokenResponse"/> /// For cross-realm (federated) scenarios it can contain a HomeRealm Uri by itself, or also include a <see cref="SecurityTokenResponse"/> from the federated realm /// </remarks> protected XrmServiceManager(Uri serviceUri, AuthenticationCredentials credentials) { this.ServiceUri = serviceUri; this.ServiceManagement = ServiceConfigurationFactory.CreateManagement <TService>(serviceUri); Authenticate(credentials); }
/// <summary> /// Handles Authenticate message /// </summary> /// <param name="ct"></param> /// <param name="hi"></param> /// <returns></returns> public string Authenticate(HttpListenerContext ct, ActionInfo hi) { // Get an Object from the request. AuthenticationCredentials AuthCredentials = GetRequestObject <AuthenticationCredentials>(ct); DataLogics DataBase = new DataLogics(); bool loginSucess = DataBase.Authenticate(AuthCredentials.UserName, AuthCredentials.Password); // The return result. AuthenticationResult result = new AuthenticationResult(); if (!loginSucess) { result.Status = AuthenticationStatus.Failed; return(GetResponseString <AuthenticationResult>(result, ct)); } // Login is okej. Lets continue. result.Status = AuthenticationStatus.Success; // Always create a new sessionCookie on Authenticate. Cookie SessionCookie = HttpUtils.NewSessionCookie(ct.Request.Url.Host); // Add Cookie to Cookies list. sessionCookies.Add(SessionCookie); // Send cookie to client. ct.Response.SetCookie(SessionCookie); // result.ClientDeviceSecret = guid.ToString(); if (DataBase.SaveCookie(SessionCookie.Value, AuthCredentials.UserName)) { Logger.Error(String.Format("Couldn't save sessionCookie {0} for user {1} to database", SessionCookie.ToString(), AuthCredentials.UserName)); } return(GetResponseString <AuthenticationResult>(result, ct)); }
/// <summary> /// Get the discovery service proxy based on existing configuration data. /// Added new way of getting discovery proxy. /// Also preserving old way of getting discovery proxy to support old scenarios. /// </summary> /// <returns>An instance of DiscoveryServiceProxy</returns> private DiscoveryServiceProxy GetDiscoveryProxy() { IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(DiscoveryUri); Authentication = serviceManagement.AuthenticationType; // Get the logon credentials. _userCredentials = GetUserLogonCredentials(this._user, this._password, this._domain); AuthenticationCredentials authCredentials = new AuthenticationCredentials(); if (!String.IsNullOrWhiteSpace(this.UserPrincipalName)) { // Try to authenticate the Federated Identity organization with UserPrinicipalName. authCredentials.UserPrincipalName = this.UserPrincipalName; try { AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials); DiscoveryServiceProxy discoveryProxy = new DiscoveryServiceProxy(serviceManagement, tokenCredentials.SecurityTokenResponse); // Checking authentication by invoking some SDK methods. OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy); return(discoveryProxy); } catch (System.ServiceModel.Security.SecurityAccessDeniedException ex) { // If authentication failed using current UserPrincipalName, // request UserName and Password to try to authenticate using user credentials. if (ex.Message.Contains("Access is denied.")) { this.AuthFailureCount += 1; authCredentials.UserPrincipalName = String.Empty; _userCredentials = GetUserLogonCredentials(this._user, this._password, this._domain); } else { throw ex; } } } // Resetting credentials in the AuthenicationCredentials. if (Authentication != AuthenticationProviderType.ActiveDirectory) { authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials = UserCredentials; if (Authentication == AuthenticationProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = UserCredentials; } // Try to authenticate with the user credentials. AuthenticationCredentials tokenCredentials1 = serviceManagement.Authenticate(authCredentials); return(new DiscoveryServiceProxy(serviceManagement, tokenCredentials1.SecurityTokenResponse)); } // For an on-premises environment. return(new DiscoveryServiceProxy(serviceManagement, UserCredentials)); }
//[WebInvoke(Method = "POST", UriTemplate = "/LogoutWithCredentials")] public bool LogoutWithCredentials(AuthenticationCredentials credentials) { var request = new RestRequest(this.ServiceUrl + "/LogoutWithCredentials", Method.POST); request.AddParameter("application/json", SerializeObject(credentials), ParameterType.RequestBody); return(ExecuteRequestFor <bool>(request)); }
public async Task <AccessToken> Token(AuthenticationCredentials credentials) { ServiceContract.RequireNotNull(credentials, nameof(credentials)); ServiceContract.RequireNotNullOrWhitespace(credentials.ClientId, nameof(credentials.ClientId)); ServiceContract.RequireNotNullOrWhitespace(credentials.ClientSecret, nameof(credentials.ClientSecret)); return(await _authenticationService.GetTokenForTenant(credentials)); }
//[WebInvoke(Method = "POST", UriTemplate = "/Authenticate")] public AuthenticationResult AuthenticateUser(AuthenticationCredentials credentials) { var request = new RestRequest(this.ServiceUrl + "/Authenticate", Method.POST); request.AddParameter("application/json", SerializeObject(credentials), ParameterType.RequestBody); return(ExecuteRequestFor <AuthenticationResult>(request)); }
/// <summary> /// Create a node endpoint client factory instance that can be used to create node client endpoint accessors. Use this /// method instead of CreateClientFactory() if you want to call INodeEndpointClientFactory.Make() without having to pass /// in the NAAS authentication credentials each time. /// </summary> /// <param name="defaultCredentials">The NAAS default authentication credentials to assign (unless specified otherwise) to /// the node client endpoint accessors returned from INodeEndpointClientFactory.Make().</param> /// <returns>The <see cref="INodeEndpointClientFactory"/> instance that can be used to create <see cref="INodeEndpointClient"/> node client /// endpoint accessors.</returns> public static INodeEndpointClientFactory CreateClientFactory(AuthenticationCredentials defaultCredentials) { NodeEndpointClientFactory factory = new NodeEndpointClientFactory(); factory.DefaultAuthenticationCredentials = defaultCredentials; factory.Init(); return(factory); }
private static OrganizationServiceProxy GetProxyService() { IServiceManagement <IDiscoveryService> serviceManagement = DynamicsCrmService.GetDiscoveryService("http://10.10.30.6:5555"); IServiceManagement <IOrganizationService> orgServiceManagement = DynamicsCrmService.GetOrganisationService("http://10.10.30.6:5555", "crm-epm"); AuthenticationCredentials authenticationCredentials = GetCredentials(serviceManagement.AuthenticationType, "CRM-001", "Energy4321!", "ENOMOS"); return(GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, authenticationCredentials)); }
private TProxy GetProxy <TService, TProxy>(Uri discoveryUri) where TService : class where TProxy : ServiceProxy <TService> { // Get appropriate Uri from Configuration. Uri serviceUri = discoveryUri; // Set service management for either organization service Uri or discovery service Uri. // For organization service Uri, if service management exists // then use it from cache. Otherwise create new service management for current organization. IServiceManagement <TService> serviceManagement = ServiceConfigurationFactory.CreateManagement <TService>( serviceUri); var decryptedPassword = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); var credentials = new ClientCredentials(); credentials.UserName.UserName = UserName; credentials.UserName.Password = decryptedPassword; // Set the credentials. AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials = credentials; Type classType; // Obtain discovery/organization service proxy for Federated, // Microsoft account and OnlineFederated environments. AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate( authCredentials); // Set classType to ManagedTokenDiscoveryServiceProxy. classType = typeof(ManagedTokenDiscoveryServiceProxy); // Invokes ManagedTokenOrganizationServiceProxy or ManagedTokenDiscoveryServiceProxy // (IServiceManagement<TService>, SecurityTokenResponse) constructor. var obj = (TProxy)classType .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) }) .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse }); return(obj); }
public CrmConnection(string orgUrl, string username, string password) { if (string.IsNullOrEmpty(orgUrl)) throw new NullReferenceException("OrganisationServiceUrl"); if (string.IsNullOrEmpty(username)) throw new NullReferenceException("Username"); if (string.IsNullOrEmpty(password)) throw new NullReferenceException("Password"); this._organisationServiceUrl = orgUrl; this._client = new AuthenticationCredentials(); this._client.ClientCredentials.UserName.UserName = username; this._client.ClientCredentials.UserName.Password = password; }
//public List<ServerConfigurationItem> GetServerConfigurations() /// <summary> /// Obtains the server connection information including the target organization's /// Uri and user logon credentials from the user. /// </summary> public virtual Configuration GetServerConfiguration() { Boolean ssl; Boolean addConfig; int configNumber; // Read the configuration from the disk, if it exists, at C:\Users\<username>\AppData\Roaming\CrmServer\Credentials.xml. Boolean isConfigExist = ReadConfigurations(); // Check if server configuration settings are already available on the disk. if (isConfigExist) { // List of server configurations that are available from earlier saved settings. Console.Write("\n(0) Add New Server Configuration (Maximum number up to 9)\t"); for (int n = 0; n < configurations.Count; n++) { String user; switch (configurations[n].EndpointType) { case AuthenticationProviderType.ActiveDirectory: if (configurations[n].Credentials != null) user = configurations[n].Credentials.Windows.ClientCredential.Domain + "\\" + configurations[n].Credentials.Windows.ClientCredential.UserName; else user = "******"; break; default: if (configurations[n].Credentials != null) user = configurations[n].Credentials.UserName.UserName; else user = "******"; break; } Console.Write("\n({0}) Server: {1}, Org: {2}, User: {3}\t", n + 1, configurations[n].ServerAddress, configurations[n].OrganizationName, user); } Console.WriteLine(); Console.Write("\nSpecify the saved server configuration number (1-{0}) [{0}] : ", configurations.Count); String input = Console.ReadLine(); Console.WriteLine(); if (input == String.Empty) input = configurations.Count.ToString(); if (!Int32.TryParse(input, out configNumber)) configNumber = -1; if (configNumber == 0) { addConfig = true; } else if (configNumber > 0 && configNumber <= configurations.Count) { // Return the organization Uri. config = configurations[configNumber - 1]; // Reorder the configuration list and save it to file to save the recent configuration as a latest one. if (configNumber != configurations.Count) { Configuration temp = configurations[configurations.Count - 1]; configurations[configurations.Count - 1] = configurations[configNumber - 1]; configurations[configNumber - 1] = temp; SaveConfigurations(); } addConfig = false; } else throw new Exception("The specified server configuration does not exist."); } else addConfig = true; if (addConfig) { // Get the server address. If no value is entered, default to Microsoft Dynamics // CRM Online in the North American data center. config.ServerAddress = GetServerAddress(out ssl); if (String.IsNullOrWhiteSpace(config.ServerAddress)) config.ServerAddress = "crm.dynamics.com"; // One of the Microsoft Dynamics CRM Online data centers. if (config.ServerAddress.EndsWith(".dynamics.com", StringComparison.InvariantCultureIgnoreCase)) { // Check if the organization is provisioned in Microsoft Office 365. if (GetOrgType(config.ServerAddress)) { config.DiscoveryUri = new Uri(String.Format("https://disco.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); } else { config.DiscoveryUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); // Get or set the device credentials. This is required for Windows Live ID authentication. config.DeviceCredentials = GetDeviceCredentials(); } } // Check if the server uses Secure Socket Layer (https). else if (ssl) config.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); else config.DiscoveryUri = new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); // Get the target organization. config.OrganizationUri = GetOrganizationAddress(); configurations.Add(config); int length = configurations.Count; int i = length - 2; // Check if a new configuration already exists. // If found, reorder list to show latest in use. while (i > 0) { if (configurations[configurations.Count - 1].Equals(configurations[i])) { configurations.RemoveAt(i); } i--; } // Set max configurations to 9 otherwise overwrite existing one. if (configurations.Count > 9) { configurations.RemoveAt(0); } SaveConfigurations(); } else { // Get the existing user's logon credentials. config.Credentials = GetUserLogonCredentials(); } // Set IServiceManagement for the current organization. IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>( config.OrganizationUri); config.OrganizationServiceManagement = orgServiceManagement; // Set SecurityTokenResponse for the current organization. if (config.EndpointType != AuthenticationProviderType.ActiveDirectory) { // Set the credentials. AuthenticationCredentials authCredentials = new AuthenticationCredentials(); // If UserPrincipalName exists, use it. Otherwise, set the logon credentials from the configuration. if (!String.IsNullOrWhiteSpace(config.UserPrincipalName)) { authCredentials.UserPrincipalName = config.UserPrincipalName; } else { authCredentials.ClientCredentials = config.Credentials; if (config.EndpointType == AuthenticationProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; } } AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); if (tokenCredentials != null) { if (tokenCredentials.SecurityTokenResponse != null) config.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse; } } return config; }
public virtual Configuration GetServerConfiguration(String u_name, String P_word,int a) { ReadConfigurations(); configurations.Clear(); config.ServerAddress = "crm.dynamics.com"; config.DiscoveryUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); config.DeviceCredentials = GetDeviceCredentials(); config.OrganizationUri = GetOrganizationAddress(u_name,P_word,a); // Set IServiceManagement for the current organization. IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(config.OrganizationUri); config.OrganizationServiceManagement = orgServiceManagement; AuthenticationCredentials authCredentials = new AuthenticationCredentials(); // If UserPrincipalName exists, use it. Otherwise, set the logon credentials from the configuration. authCredentials.ClientCredentials = config.Credentials; if (config.EndpointType == AuthenticationProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; } AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); if (tokenCredentials != null) { if (tokenCredentials.SecurityTokenResponse != null) config.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse; } return config; }
public virtual Configuration Gettest(String u_name, String P_word, int a) { ReadConfigurations(); configurations.Clear(); config.ServerAddress = "crm.dynamics.com"; config.DiscoveryUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); config.DeviceCredentials = GetDeviceCredentials(); config.OrganizationUri = GetOrganizationAddress(u_name, P_word, a); IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(config.OrganizationUri); config.OrganizationServiceManagement = orgServiceManagement; AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials = config.Credentials; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); config.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse; return config; }
private DiscoveryServiceProxy GetDiscoveryProxy() { IServiceManagement<IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IDiscoveryService>( config.DiscoveryUri); config.EndpointType = serviceManagement.AuthenticationType; config.Credentials = GetUserLogonCredentials(); AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials = config.Credentials; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; AuthenticationCredentials tokenCredentials1 = serviceManagement.Authenticate(authCredentials); return new DiscoveryServiceProxy(serviceManagement,tokenCredentials1.SecurityTokenResponse); }
public virtual Configuration GetServerConfiguration() { Boolean addConfig; // Read the configuration from the disk, if it exists, at C:\Users\<username>\AppData\Roaming\CrmServer\Credentials.xml. Boolean isConfigExist = ReadConfigurations(); configurations.Clear(); addConfig = true; if (addConfig) { config.ServerAddress = "crm.dynamics.com"; config.DiscoveryUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress)); config.OrganizationUri = new Uri(String.Format("https://crmnaorg939c6.api.crm.dynamics.com/XRMServices/2011/Organization.svc")); config.DeviceCredentials = GetDeviceCredentials(); config.OrganizationUri = GetOrganizationAddress(); } // Set IServiceManagement for the current organization. IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>( config.OrganizationUri); config.OrganizationServiceManagement = orgServiceManagement; // Set the credentials. AuthenticationCredentials authCredentials = new AuthenticationCredentials(); // If UserPrincipalName exists, use it. Otherwise, set the logon credentials from the configuration. authCredentials.ClientCredentials = config.Credentials; if (config.EndpointType == AuthenticationProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; } AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); if (tokenCredentials != null) { if (tokenCredentials.SecurityTokenResponse != null) config.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse; } return config; }
/// <summary> /// Get the discovery service proxy based on existing configuration data. /// Added new way of getting discovery proxy. /// Also preserving old way of getting discovery proxy to support old scenarios. /// </summary> /// <returns>An instance of DiscoveryServiceProxy</returns> private DiscoveryServiceProxy GetDiscoveryProxy() { IServiceManagement<IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IDiscoveryService>( config.DiscoveryUri); // Get the EndpointType. config.EndpointType = serviceManagement.AuthenticationType; // Get the logon credentials. config.Credentials = GetUserLogonCredentials(); AuthenticationCredentials authCredentials = new AuthenticationCredentials(); if (!String.IsNullOrWhiteSpace(config.UserPrincipalName)) { // Try to authenticate the Federated Identity organization with UserPrinicipalName. authCredentials.UserPrincipalName = config.UserPrincipalName; try { AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate( authCredentials); DiscoveryServiceProxy discoveryProxy = new DiscoveryServiceProxy(serviceManagement, tokenCredentials.SecurityTokenResponse); // Checking authentication by invoking some SDK methods. OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy); return discoveryProxy; } catch (System.ServiceModel.Security.SecurityAccessDeniedException ex) { // If authentication failed using current UserPrincipalName, // request UserName and Password to try to authenticate using user credentials. if (ex.Message.Contains("Access is denied.")) { config.AuthFailureCount += 1; authCredentials.UserPrincipalName = String.Empty; config.Credentials = GetUserLogonCredentials(); } else { throw ex; } } // You can also catch other exceptions to handle a specific situation in your code, for example, // System.ServiceModel.Security.ExpiredSecurityTokenException // System.ServiceModel.Security.MessageSecurityException // System.ServiceModel.Security.SecurityNegotiationException } // Resetting credentials in the AuthenicationCredentials. if (config.EndpointType != AuthenticationProviderType.ActiveDirectory) { authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials = config.Credentials; if (config.EndpointType == AuthenticationProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials; } // Try to authenticate with the user credentials. AuthenticationCredentials tokenCredentials1 = serviceManagement.Authenticate( authCredentials); return new DiscoveryServiceProxy(serviceManagement, tokenCredentials1.SecurityTokenResponse); } // For an on-premises environment. return new DiscoveryServiceProxy(serviceManagement, config.Credentials); }
private AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType) { //Load the credentials from the Web.config first //string userName = ConfigurationManager.AppSettings["CRM_Username"]; //string password = ConfigurationManager.AppSettings["CRM_Password"]; //string domain = ConfigurationManager.AppSettings["CRM_Domain"]; string userName = "******"; string password = "******"; string domain = ""; //Load the auth type string authenticationType = ConfigurationManager.AppSettings["CRM_AuthenticationType"]; AuthenticationCredentials authCreds = new AuthenticationCredentials(); switch (authenticationType) { case "ActiveDirectory": authCreds.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(userName, password, domain); break; case "LiveId": authCreds.ClientCredentials.UserName.UserName = userName; authCreds.ClientCredentials.UserName.Password = password; authCreds.SupportingCredentials = new AuthenticationCredentials(); authCreds.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice(); break; case "Online": // For Federated and OnlineFederated environments. authCreds.ClientCredentials.UserName.UserName = userName; authCreds.ClientCredentials.UserName.Password = password; break; case "SSO": //Single Sign On // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. authCreds.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; //Windows/Kerberos break; default: // Online authCreds.ClientCredentials.UserName.UserName = userName; authCreds.ClientCredentials.UserName.Password = password; break; } return authCreds; }