public static void AuthorizeUsingRefreshToken(Dinero dinero, string clientId, string clientSecret) { //Calling authorize against the api var token = dinero.Authorize(); //Get refresh token var refreshtoken = token.RefreshToken; if (refreshtoken == null) { Console.WriteLine("You do not have permission to use access tokens."); return; } Console.WriteLine("Refreshtoken obtained."); //TODO: persist the refresh token in db for later use Console.WriteLine("Instantiate new Dinero object using refresh token."); var client = new ClientCredentials(clientId, clientSecret); //instantiate using refresh token var dinero2 = new Dinero(client, new RefreshToken(refreshtoken)); //Calling authorize against the api dinero2.Authorize(); Console.WriteLine("Authorization successfull."); }
public void Init() { fixture = new Fixture(); credentials = fixture.Create<ClientCredentials>(); serverUri = fixture.Create<Uri>().ToString(); classUnderTests = fixture.Create<ClientFactory>(); }
private DineroSettings(ClientCredentials client, DineroOauth2Client.AuthorizationBodyContent bodyContent) { if (client == null) throw new ArgumentNullException("client"); if (bodyContent == null) throw new ArgumentNullException("bodyContent"); Client = client; BodyContent = bodyContent; }
private const string PathToSavePdfsTo = null; // <- Replace with path static int Main() { var client = new ClientCredentials(ClientId, ClientSecret); var apiKey = new ApiKey(ApiKey); var dinero = new Dinero(client, apiKey, OrganizationId); //Calling authorize against the api dinero.Authorize(); while (true) { PrintMenu(); var userChoice = GetInput(); if (userChoice.Equals("q", StringComparison.InvariantCultureIgnoreCase)) { return 0; } PerformAction(dinero, userChoice).ContinueWith(t => Pause()).Wait(); } }
public static IHttpClientBuilder AddAuthentication(this IHttpClientBuilder builder, ClientCredentials credentials, string identityAuthority) { builder.Services.TryAddSingleton <AccessTokensCacheManager>(); builder.AddHttpMessageHandler(provider => CreateDelegatingHandler(provider, credentials, identityAuthority)); return(builder); }
public IOrganizationService crea_ServicioCRM() { bool esIFD = Convert.ToBoolean(this.IFD); ClientCredentials Credencial = new ClientCredentials(); if (esIFD) { Credencial.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials; Credencial.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; Credencial.UserName.UserName = CredencialDominio + @"\" + CredencialUsuario; Credencial.UserName.Password = CredencialContrasena; } else { System.Net.NetworkCredential credenciales = new System.Net.NetworkCredential(CredencialUsuario, CredencialContrasena, CredencialDominio); Credencial.Windows.ClientCredential = credenciales; } Uri HomeRealmUri; HomeRealmUri = null; if (http.Equals("http")) { if (TipoCRM == "OnLine") { CrmConnection conexion = CrmConnection.Parse("Url=https://" + CRMServidor + "; Username="******"; Password="******";"); int int_timeout = 0; if (int.TryParse(TimeOut, out int_timeout)) { conexion.Timeout = new TimeSpan(0, int_timeout, 0); } OrganizationService OService = new OrganizationService(conexion); return((IOrganizationService)OService); } else { Uri OrganizationUri = new Uri("http://" + CRMServidor + "/" + CRMOrganizationName + "/XRMServices/2011/Organization.svc"); OrganizationServiceProxy _serviceProxy; _serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credencial, null); //DESCOMENTAR //_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); return((IOrganizationService)_serviceProxy); } } else { if (CertificateValidation.Length > 0) { bool certificadoValidacion = Convert.ToBoolean(CertificateValidation); Uri OrganizationUri = new Uri("https://" + CRMServidor + "/XRMServices/2011/Organization.svc"); if (certificadoValidacion) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallBack); } else { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallBackTrue); } OrganizationServiceProxy _serviceProxy; _serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credencial, null); //DESCOMENTAR //_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); return((IOrganizationService)_serviceProxy); } else { return(null); } } }
private Token GetISpotifyWebApiToken() { return(ClientCredentials.GetToken(_authParameters)); }
protected async Task ValidateSecret(TClient client, TokenRequest tokenRequest, ClientCredentials clientCredentials) { if (tokenRequest.ClientId.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(tokenRequest.ClientId), tokenRequest.GetTypeName()); } clientCredentials.Validate(); if (client?.Secrets.Count() <= 0) { throw new OAuthRequestException($"Invalid client secret. Secret not configured for client id '{tokenRequest.ClientId}'.") { RouteBinding = RouteBinding, Error = IdentityConstants.ResponseErrors.InvalidGrant }; } foreach (var secret in client.Secrets) { if (await secretHashLogic.ValidateSecretAsync(secret, clientCredentials.ClientSecret)) { logger.ScopeTrace($"Down, OAuth Client id '{tokenRequest.ClientId}. Client secret valid.", triggerEvent: true); return; } } throw new OAuthRequestException($"Invalid client secret for client id '{tokenRequest.ClientId}'.") { RouteBinding = RouteBinding, Error = IdentityConstants.ResponseErrors.InvalidGrant }; }
public OAuthRequestAuthenticator(ClientCredentials credentials, AccessToken token) { this.credentials = credentials; this.token = token; }
/// <summary> /// Sets new client credentials on the channelfactory /// </summary> /// <param name="channelFactory"> /// The channel factory. /// </param> /// <param name="clientCredentials"> /// The new client credentials. /// </param> /// <typeparam name="T"> /// The service contract /// </typeparam> public static void SetClientCredentials <T>(this ChannelFactory <T> channelFactory, ClientCredentials clientCredentials) { var defaultCredentials = channelFactory.Endpoint.Behaviors.Find <ClientCredentials>(); channelFactory.Endpoint.Behaviors.Remove(defaultCredentials); channelFactory.Endpoint.Behaviors.Add(clientCredentials); }
public DineroSettings(ClientCredentials client, DineroCredentials user, IEnumerable<string> scopes = null) : this(client, new DineroOauth2Client.DineroCredentialsBodyContent(user, scopes)) { }
public DineroSettings(ClientCredentials client, RefreshToken refreshToken) : this(client, new DineroOauth2Client.RefreshTokenBodyContent(refreshToken)) { }
public void Should_secure_restricted_environments() { _ruleData.UnitTest_Clear(); SetupSecureEnvironments(); _ruleData.SetDefaultEnvironment(null, "Production"); var devClient = new ClientCredentials { IpAddress = "192.168.3.54" }; var config1 = _ruleData.UnitTest_GetRuleSet(devClient, null); Assert.AreEqual(3, config1.Environments.Count); Assert.AreEqual("Production", config1.Environments[0].EnvironmentName); Assert.AreEqual("Staging", config1.Environments[1].EnvironmentName); Assert.AreEqual("Development", config1.Environments[2].EnvironmentName); Assert.AreEqual("web1", config1.Environments[0].Machines[0].Name); Assert.AreEqual("web2", config1.Environments[0].Machines[1].Name); Assert.AreEqual("web3", config1.Environments[0].Machines[2].Name); try { _ruleData.SetEnvironments(devClient, new List<EnvironmentDto> { new EnvironmentDto { EnvironmentName = "Production", Machines = new List<MachineDto> { new MachineDto {Name = "dev1"} }, }, new EnvironmentDto { EnvironmentName = "Development", Machines = new List<MachineDto> { new MachineDto {Name = "dev1"}, new MachineDto {Name = "dev2"}, new MachineDto {Name = "dev3"} }, } }); Assert.Fail("Should throw exception when updating restricted environments"); } catch { } var config2 = _ruleData.UnitTest_GetRuleSet(devClient, null); Assert.AreEqual(3, config2.Environments.Count); Assert.AreEqual("Production", config2.Environments[0].EnvironmentName); Assert.AreEqual("Staging", config2.Environments[1].EnvironmentName); Assert.AreEqual("Development", config2.Environments[2].EnvironmentName); Assert.AreEqual("web1", config2.Environments[0].Machines[0].Name); Assert.AreEqual("web2", config2.Environments[0].Machines[1].Name); Assert.AreEqual("web3", config2.Environments[0].Machines[2].Name); Assert.AreEqual("stage1", config2.Environments[1].Machines[0].Name); Assert.AreEqual("stage2", config2.Environments[1].Machines[1].Name); Assert.AreEqual("stage3", config2.Environments[1].Machines[2].Name); Assert.AreEqual("dev1", config2.Environments[2].Machines[0].Name); Assert.AreEqual("dev2", config2.Environments[2].Machines[1].Name); Assert.AreEqual("dev3", config2.Environments[2].Machines[2].Name); var stagingClient = new ClientCredentials { IpAddress = "192.168.1.2" }; try { _ruleData.SetEnvironments(stagingClient, new List<EnvironmentDto> { new EnvironmentDto { EnvironmentName = "Production", Machines = new List<MachineDto> { new MachineDto{Name="dev1"} }, }, new EnvironmentDto { EnvironmentName = "Development", Machines = new List<MachineDto> { new MachineDto{Name="dev1"}, new MachineDto{Name="dev2"}, new MachineDto{Name="dev3"} }, } }); Assert.Fail("Should throw exception when updating restricted environments"); } catch { } var config3 = _ruleData.UnitTest_GetRuleSet(stagingClient, null); Assert.AreEqual(2, config3.Environments.Count); Assert.AreEqual("Production", config3.Environments[0].EnvironmentName); Assert.AreEqual("Development", config3.Environments[1].EnvironmentName); Assert.AreEqual("web1", config3.Environments[0].Machines[0].Name); Assert.AreEqual("web2", config3.Environments[0].Machines[1].Name); Assert.AreEqual("web3", config3.Environments[0].Machines[2].Name); Assert.AreEqual("dev1", config3.Environments[1].Machines[0].Name); Assert.AreEqual("dev2", config3.Environments[1].Machines[1].Name); Assert.AreEqual("dev3", config3.Environments[1].Machines[2].Name); var prodClient = new ClientCredentials { IpAddress = "192.168.0.2" }; _ruleData.SetEnvironments(prodClient, new List<EnvironmentDto> { new EnvironmentDto { EnvironmentName = "Production", Machines = new List<MachineDto> { new MachineDto{Name="dev1"} }, }, new EnvironmentDto { EnvironmentName = "Development", Machines = new List<MachineDto> { new MachineDto{Name="dev1"}, new MachineDto{Name="dev2"}, new MachineDto{Name="dev3"} }, } }); var config4 = _ruleData.UnitTest_GetRuleSet(prodClient, null); Assert.AreEqual(2, config4.Environments.Count); Assert.AreEqual("Production", config4.Environments[0].EnvironmentName); Assert.AreEqual("Development", config4.Environments[1].EnvironmentName); Assert.AreEqual("dev1", config4.Environments[0].Machines[0].Name); Assert.AreEqual("dev1", config4.Environments[1].Machines[0].Name); Assert.AreEqual("dev2", config4.Environments[1].Machines[1].Name); Assert.AreEqual("dev3", config4.Environments[1].Machines[2].Name); }
public void Should_not_update_rules_for_restricted_environments() { _ruleData.UnitTest_Clear(); SetupSecureEnvironments(); var productionClient = new ClientCredentials { IpAddress = "192.168.0.32" }; var developmentClient = new ClientCredentials { IpAddress = "192.168.2.161" }; var draftRules = _ruleData.UnitTest_GetRuleSet(null, null); var version = draftRules.RuleVersion.Version; var exception = false; try { _ruleData.UpdateRule( developmentClient, version, "Production Environment", new RuleDto { RuleName = "Production Environment", Environment = "Development", Application = "MyNewApp" }); } catch { exception = true; } var newRules = _ruleData.UnitTest_GetRuleSet(productionClient, null).RuleVersion.Rules; Assert.IsTrue(exception); Assert.AreEqual(3, newRules.Count); }
public void Should_not_retrieve_rules_from_restricted_environment() { _ruleData.UnitTest_Clear(); SetupSecureEnvironments(); var productionClient = new ClientCredentials { IpAddress = "192.168.0.32" }; var stagingClient = new ClientCredentials { IpAddress = "192.168.1.99" }; var developmentClient = new ClientCredentials { IpAddress = "192.168.2.161" }; var productionRules = _ruleData.UnitTest_GetRuleSet(productionClient, null).RuleVersion; var stagingRules = _ruleData.UnitTest_GetRuleSet(stagingClient, null).RuleVersion; var developmentRules = _ruleData.UnitTest_GetRuleSet(developmentClient, null).RuleVersion; Assert.AreEqual(3, productionRules.Rules.Count); Assert.AreEqual(2, stagingRules.Rules.Count); Assert.AreEqual(1, developmentRules.Rules.Count); Assert.AreEqual("Production Environment", productionRules.Rules[2].RuleName); Assert.AreEqual("Staging Environment", productionRules.Rules[1].RuleName); Assert.AreEqual("Development Environment", productionRules.Rules[0].RuleName); Assert.AreEqual("Staging Environment", stagingRules.Rules[1].RuleName); Assert.AreEqual("Development Environment", stagingRules.Rules[0].RuleName); Assert.AreEqual("Development Environment", developmentRules.Rules[0].RuleName); }
public ManagedTokenDiscoveryServiceProxy(IServiceManagement <IDiscoveryService> serviceManagement, ClientCredentials userCredentials) : base(serviceManagement, userCredentials) { this._proxyManager = new AutoRefreshSecurityToken <DiscoveryServiceProxy, IDiscoveryService>(this); }
public ManagedTokenOrganizationServiceProxy(IServiceManagement <IOrganizationService> serviceManagement, ClientCredentials userCredentials) : base(serviceManagement, userCredentials) { this._proxyManager = new AutoRefreshSecurityToken <OrganizationServiceProxy, IOrganizationService>(this); }
private void Initialize(bool useWebStream, bool useHttpsWebStream, IEnumerable <Uri> baseAddresses) { List <Uri> uris = new List <Uri>(); foreach (Uri baseAddress in baseAddresses) { if (base.Address == null) { base.Address = baseAddress; } UriBuilder uriBuilder = new UriBuilder(baseAddress); if (!this.Settings.GatewayMode && string.Compare(uriBuilder.Scheme, "sb", StringComparison.OrdinalIgnoreCase) != 0) { ExceptionTrace exception = Microsoft.ServiceBus.Messaging.FxTrace.Exception; string invalidUriScheme = Resources.InvalidUriScheme; object[] scheme = new object[] { uriBuilder.Scheme, "sb" }; throw exception.AsError(new ArgumentException(Microsoft.ServiceBus.SR.GetString(invalidUriScheme, scheme)), null); } if (!useWebStream) { uriBuilder.Scheme = SbmpProtocolDefaults.TransportUriScheme; } else { uriBuilder.Scheme = "sb"; uriBuilder.Port = (useHttpsWebStream ? RelayEnvironment.RelayHttpsPort : RelayEnvironment.RelayHttpPort); } if (!this.Settings.GatewayMode && uriBuilder.Port == -1) { if (!useWebStream) { uriBuilder.Port = RelayEnvironment.RelayNmfPort; } else { uriBuilder.Port = (useHttpsWebStream ? RelayEnvironment.RelayHttpsPort : RelayEnvironment.RelayHttpPort); } } MessagingUtilities.EnsureTrailingSlash(uriBuilder); uris.Add(uriBuilder.Uri); } this.baseAddresses = null; this.BaseAddress = uris.First <Uri>(); bool useSslStreamSecurity = this.Settings.UseSslStreamSecurity; CustomBinding customBinding = SbmpProtocolDefaults.CreateBinding(false, useWebStream, useHttpsWebStream, 2147483647, useSslStreamSecurity, this.Settings.EndpointIdentity); DuplexRequestBindingElement duplexRequestBindingElement = new DuplexRequestBindingElement() { ClientMode = !this.Settings.GatewayMode, IncludeExceptionDetails = true }; DuplexRequestBindingElement duplexRequestBindingElement1 = duplexRequestBindingElement; int num = 0; if (!this.Settings.GatewayMode) { RedirectBindingElement redirectBindingElement = new RedirectBindingElement() { EnableRedirect = this.Settings.EnableRedirect, UseSslStreamSecurity = useSslStreamSecurity, IncludeExceptionDetails = true, EndpointIdentity = this.Settings.EndpointIdentity }; RedirectBindingElement redirectBindingElement1 = redirectBindingElement; int num1 = num; num = num1 + 1; customBinding.Elements.Insert(num1, new ReconnectBindingElement(uris)); int num2 = num; num = num2 + 1; customBinding.Elements.Insert(num2, redirectBindingElement1); } int num3 = num; num = num3 + 1; customBinding.Elements.Insert(num3, new ReconnectBindingElement(uris)); int num4 = num; num = num4 + 1; customBinding.Elements.Insert(num4, duplexRequestBindingElement1); BindingParameterCollection bindingParameterCollection = new BindingParameterCollection(); if (useSslStreamSecurity) { ClientCredentials clientCredential = new ClientCredentials(); clientCredential.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; clientCredential.ServiceCertificate.Authentication.CustomCertificateValidator = RetriableCertificateValidator.Instance; bindingParameterCollection.Add(clientCredential); } this.ChannelFactory = customBinding.BuildChannelFactory <IRequestSessionChannel>(bindingParameterCollection); this.MessageVersion = customBinding.MessageVersion; this.ResourceManager = SbmpResourceManager.Instance; this.acceptMessageSessionForNamespaceLinkSettings = new CreateControlLinkSettings(this, string.Empty, "||", MessagingEntityType.Namespace, null); EventHandler eventHandler = new EventHandler(this.OnInnerFactoryFaulted); this.ChannelFactory.SafeAddFaulted(eventHandler); }
/// <summary> /// Requests a bearer token. /// </summary> /// <param name="stsAddress">The STS address.</param> /// <param name="appliesTo">The realm address.</param> /// <param name="binding">The binding.</param> /// <param name="credentials">The credentials.</param> /// <returns>A SecurityToken</returns> public static SecurityToken Issue(EndpointAddress stsAddress, EndpointAddress appliesTo, Binding binding, ClientCredentials credentials) { RequestSecurityTokenResponse rstr; var rst = CreateBearerRst(appliesTo); return(Issue(stsAddress, binding, credentials, rst, out rstr)); }
public override Guid WriteToCDS(string cdsUrl, string cdsUserName, string cdsPassword) { Guid allergyIntolernaceId = Guid.Empty; try { #region Get our Login Information // setup the variables OrganizationServiceProxy _serviceProxy; // homeRealmUri will stay null for now Uri homeRealmUri = null; // setup credentials from whatever is in the app.config ClientCredentials credentials; // same for organizationuri comes from app.config Uri organizationUri; // set the organization uri from what was in the app.config organizationUri = new Uri(cdsUrl); credentials = new ClientCredentials(); credentials.UserName.UserName = cdsUserName; credentials.UserName.Password = cdsPassword; #endregion ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (_serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null)) { // To impersonate set the GUID of CRM user here (which I merely took from CRM itself // would need not to use this caller id in the future (as it will change per instance of CRM) //_serviceProxy.CallerId = new Guid("14D40CB7-81D5-E311-93F5-00155D00330C"); _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); //enable using proxy types _serviceProxy.EnableProxyTypes(); HealthCDM.msemr_allergyintolerance addAllergyIntolerance = new HealthCDM.msemr_allergyintolerance(); addAllergyIntolerance.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PatientId))); addAllergyIntolerance.msemr_name = Item; addAllergyIntolerance.msemr_Code = Item; addAllergyIntolerance.msemr_Criticality = new OptionSetValue(Severity); addAllergyIntolerance.msemr_VerificationStatus = new OptionSetValue(VertificationStatus); addAllergyIntolerance.msemr_Type = new OptionSetValue(Type); try { allergyIntolernaceId = _serviceProxy.Create(addAllergyIntolerance); if (allergyIntolernaceId != Guid.Empty) { AllergyIntoleranceId = allergyIntolernaceId.ToString(); Console.WriteLine("Created Allergy Intolerance [" + AllergyIntoleranceId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("AllergyIntoleranceId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(allergyIntolernaceId); }
public void Should_not_retrieve_config_from_restricted_environment() { _ruleData.UnitTest_Clear(); SetupSecureEnvironments(); var productionClient = new ClientCredentials { IpAddress = "192.168.0.32" }; var stagingClient = new ClientCredentials { IpAddress = "192.168.1.99" }; var developmentClient = new ClientCredentials { IpAddress = "192.168.2.161" }; var web1Production = _ruleData.GetConfig(productionClient, "", "web1", "myApp", ""); var web1Staging = _ruleData.GetConfig(stagingClient, "", "web1", "myApp", ""); var web1Development = _ruleData.GetConfig(developmentClient, "", "web1", "myApp", ""); var stage2Production = _ruleData.GetConfig(productionClient, "", "stage2", "myApp", ""); var stage2Staging = _ruleData.GetConfig(stagingClient, "", "stage2", "myApp", ""); var stage2Development = _ruleData.GetConfig(developmentClient, "", "stage2", "myApp", ""); var dev1Production = _ruleData.GetConfig(productionClient, "", "dev1", "myApp", ""); var dev1Staging = _ruleData.GetConfig(stagingClient, "", "dev1", "myApp", ""); var dev1Development = _ruleData.GetConfig(developmentClient, "", "dev1", "myApp", ""); const string emptyConfig = "{}"; Assert.IsTrue(web1Production.ToString().IndexOf("web1.mysite.com") > 0); Assert.AreEqual(emptyConfig, web1Staging.ToString()); Assert.AreEqual(emptyConfig, web1Development.ToString()); Assert.IsTrue(stage2Production.ToString().IndexOf("stage2.mysite.local") > 0); Assert.IsTrue(stage2Staging.ToString().IndexOf("stage2.mysite.local") > 0); Assert.AreEqual(emptyConfig, stage2Development.ToString()); Assert.IsTrue(dev1Production.ToString().IndexOf("localhost/mysite") > 0); Assert.IsTrue(dev1Staging.ToString().IndexOf("localhost/mysite") > 0); Assert.IsTrue(dev1Development.ToString().IndexOf("localhost/mysite") > 0); }
protected virtual SecurityTokenResponse CreateUserTokenResponse(CrmConnection connection, IServiceConfiguration <IOrganizationService> config) { var homeRealmUri = connection.HomeRealmUri; var clientCredentials = connection.ClientCredentials; var deviceCredentials = connection.DeviceCredentials; if (clientCredentials == null) { throw new ConfigurationErrorsException("The connection's user credentials must be specified."); } SecurityTokenResponse userTokenResponse; if (config.AuthenticationType == AuthenticationProviderType.LiveId) { if (deviceCredentials == null || deviceCredentials.UserName == null) { throw new ConfigurationErrorsException("The connection's device credentials must be specified."); } var deviceUserName = deviceCredentials.UserName.UserName; var devicePassword = deviceCredentials.UserName.Password; if (string.IsNullOrWhiteSpace(deviceUserName)) { throw new ConfigurationErrorsException("The connection's device Id must be specified."); } if (string.IsNullOrWhiteSpace(devicePassword)) { throw new ConfigurationErrorsException("The connection's device password must be specified."); } if (devicePassword.Length < 6) { throw new ConfigurationErrorsException("The connection's device password must be at least 6 characters."); } // prepend the DevicePrefix to the device Id var extendedDeviceCredentials = new ClientCredentials(); extendedDeviceCredentials.UserName.UserName = DeviceIdManager.DevicePrefix + deviceCredentials.UserName.UserName; extendedDeviceCredentials.UserName.Password = deviceCredentials.UserName.Password; SecurityTokenResponse deviceTokenResponse; try { deviceTokenResponse = config.AuthenticateDevice(extendedDeviceCredentials); } catch (MessageSecurityException) { // try register the device credentials deviceTokenResponse = RegisterDeviceCredentials(deviceCredentials) // try re-authenticate ? config.AuthenticateDevice(extendedDeviceCredentials) : null; } Assert(deviceTokenResponse != null && deviceTokenResponse.Token != null, "The device authentication failed!"); userTokenResponse = config.Authenticate(clientCredentials, deviceTokenResponse); } else { if (homeRealmUri != null) { var appliesTo = config.PolicyConfiguration.SecureTokenServiceIdentifier; var homeRealmSecurityTokenResponse = config.AuthenticateCrossRealm(clientCredentials, appliesTo, homeRealmUri); Assert(homeRealmSecurityTokenResponse != null && homeRealmSecurityTokenResponse.Token != null, "The user authentication failed!"); userTokenResponse = config.Authenticate(homeRealmSecurityTokenResponse.Token); } else { userTokenResponse = config.Authenticate(clientCredentials); } } return(userTokenResponse); }
public static void SetCredentials(ClientCredentials clientCredentials) { clientCredentials.UserName.UserName = "******"; clientCredentials.UserName.Password = "******"; }
protected bool RegisterDeviceCredentials(ClientCredentials deviceCredentials) { var response = DeviceIdManager.RegisterDevice(deviceCredentials); return(response.IsSuccess); }
/// <summary> /// Initializes a new instance of the <see cref="WcfMessageInspectorEventArgs" /> class. /// </summary> /// <param name="message">The message of the service endpoint.</param> /// <param name="messageId">The message identifier.</param> /// <param name="isOneWay">Whether the message is one way.</param> /// <param name="validationError">The validation error.</param> /// <param name="endpoint">The endpoint.</param> /// <param name="clientCredentials">The client credentials.</param> /// <param name="serviceHostBase">The service host base.</param> public WcfMessageInspectorEventArgs(Message message, Guid messageId, bool isOneWay, string validationError, ServiceEndpoint endpoint, ClientCredentials clientCredentials, ServiceHostBase serviceHostBase) { this.Message = message; this.MessageId = messageId; this.Endpoint = endpoint; this.IsOneWay = isOneWay; this.ValidationError = validationError; this.ClientCredentials = clientCredentials; this.ServiceHost = serviceHostBase; }
static void FillBehaviorInfo(IEndpointBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance) { Fx.Assert(null != existingInstance, ""); Fx.Assert(null != behavior, ""); instance = null; if (behavior is ClientCredentials) { instance = existingInstance.NewInstance("ClientCredentials"); ClientCredentials specificBehavior = (ClientCredentials)behavior; instance.SetProperty(AdministrationStrings.SupportInteractive, specificBehavior.SupportInteractive); if (specificBehavior.ClientCertificate != null && specificBehavior.ClientCertificate.Certificate != null) { instance.SetProperty(AdministrationStrings.ClientCertificate, specificBehavior.ClientCertificate.Certificate.ToString()); } if (specificBehavior.IssuedToken != null) { string result = String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.CacheIssuedTokens, specificBehavior.IssuedToken.CacheIssuedTokens); instance.SetProperty(AdministrationStrings.IssuedToken, result); } if (specificBehavior.HttpDigest != null) { string result = String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.AllowedImpersonationLevel, specificBehavior.HttpDigest.AllowedImpersonationLevel.ToString()); instance.SetProperty(AdministrationStrings.HttpDigest, result); } if (specificBehavior.Peer != null && specificBehavior.Peer.Certificate != null) { instance.SetProperty(AdministrationStrings.Peer, specificBehavior.Peer.Certificate.ToString(true)); } if (specificBehavior.UserName != null) { instance.SetProperty(AdministrationStrings.UserName, "********"); } if (specificBehavior.Windows != null) { #pragma warning disable 618 // To suppress AllowNtlm warning. string result = String.Format(CultureInfo.InvariantCulture, "{0}: {1}, {2}: {3}", AdministrationStrings.AllowedImpersonationLevel, specificBehavior.Windows.AllowedImpersonationLevel.ToString(), AdministrationStrings.AllowNtlm, specificBehavior.Windows.AllowNtlm); #pragma warning restore 618 instance.SetProperty(AdministrationStrings.Windows, result); } } else if (behavior is MustUnderstandBehavior) { instance = existingInstance.NewInstance("MustUnderstandBehavior"); } else if (behavior is SynchronousReceiveBehavior) { instance = existingInstance.NewInstance("SynchronousReceiveBehavior"); } else if (behavior is DispatcherSynchronizationBehavior) { instance = existingInstance.NewInstance("DispatcherSynchronizationBehavior"); } else if (behavior is TransactedBatchingBehavior) { instance = existingInstance.NewInstance("TransactedBatchingBehavior"); instance.SetProperty(AdministrationStrings.MaxBatchSize, ((TransactedBatchingBehavior)behavior).MaxBatchSize); } else if (behavior is ClientViaBehavior) { instance = existingInstance.NewInstance("ClientViaBehavior"); instance.SetProperty(AdministrationStrings.Uri, ((ClientViaBehavior)behavior).Uri.ToString()); } else if (behavior is IWmiInstanceProvider) { IWmiInstanceProvider instanceProvider = (IWmiInstanceProvider)behavior; instance = existingInstance.NewInstance(instanceProvider.GetInstanceType()); instanceProvider.FillInstance(instance); } else { instance = existingInstance.NewInstance("Behavior"); } if (null != instance) { instance.SetProperty(AdministrationStrings.Type, behavior.GetType().FullName); } }
public void ConfigureClientCredentials(ClientCredentials creds, Type contractType) { }
static void Main() { { // <Snippet1> // Configure custom certificate validation. ClientCredentials creds = new ClientCredentials(); creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; creds.ServiceCertificate.Authentication.CustomCertificateValidator = new MyCertificateValidator(); // </Snippet1> } { // <Snippet2> ClientCredentials creds = new ClientCredentials(); // Configure chain trust. creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; creds.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; // </Snippet2> } { // <Snippet3> ClientCredentials creds = new ClientCredentials(); // Configure chain trust. creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; creds.ServiceCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine; // </Snippet3> } { // <Snippet4> ClientCredentials clientCreds = new ClientCredentials(); Console.WriteLine( clientCreds.ServiceCertificate.Authentication); // </Snippet4> } // Create a client with given client endpoint configuration CalculatorClient wcfClient = new CalculatorClient(); try { // set new credentials wcfClient.ChannelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials)); wcfClient.ChannelFactory.Endpoint.Behaviors.Add(new MyUserNameClientCredentials()); /* * Setting the CertificateValidationMode to PeerOrChainTrust means that if the certificate * is in the Trusted People store, then it will be trusted without performing a * validation of the certificate's issuer chain. This setting is used here for convenience so that the * sample can be run without having to have certificates issued by a certificate authority (CA). * This setting is less secure than the default, ChainTrust. The security implications of this * setting should be carefully considered before using PeerOrChainTrust in production code. */ wcfClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; // <Snippet0> ClientCredentials creds = new ClientCredentials(); // Configure peer trust. creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust; // Configure chain trust. creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; // Configure custom certificate validation. creds.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; creds.ServiceCertificate.Authentication.CustomCertificateValidator = new MyCertificateValidator(); // </Snippet0> // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = wcfClient.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Call the Subtract service operation. value1 = 145.00D; value2 = 76.54D; result = wcfClient.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); // Call the Multiply service operation. value1 = 9.00D; value2 = 81.25D; result = wcfClient.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); // Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = wcfClient.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); wcfClient.Close(); } catch (TimeoutException timeProblem) { Console.WriteLine("The service operation timed out. " + timeProblem.Message); Console.ReadLine(); wcfClient.Abort(); } catch (CommunicationException commProblem) { Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace); Console.ReadLine(); wcfClient.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
private void InitializeFactories() { ISecurityCapabilities securityCapabilities = BootstrapSecurityBindingElement.GetProperty <ISecurityCapabilities>(IssuerBindingContext); SecurityCredentialsManager securityCredentials = IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>(); if (securityCredentials == null) { securityCredentials = ClientCredentials.CreateDefaultCredentials(); } BindingContext context = IssuerBindingContext; _bootstrapSecurityBindingElement.ReaderQuotas = context.GetInnerProperty <XmlDictionaryReaderQuotas>(); if (_bootstrapSecurityBindingElement.ReaderQuotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.EncodingBindingElementDoesNotHandleReaderQuotas)); } TransportBindingElement transportBindingElement = context.RemainingBindingElements.Find <TransportBindingElement>(); if (transportBindingElement != null) { _bootstrapSecurityBindingElement.MaxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize; } SecurityProtocolFactory securityProtocolFactory = BootstrapSecurityBindingElement.CreateSecurityProtocolFactory <IRequestChannel>(IssuerBindingContext.Clone(), securityCredentials, false, IssuerBindingContext.Clone()); if (_localAddress != null) { MessageFilter issueAndRenewFilter = new SessionActionFilter(_standardsManager, IssueResponseAction.Value, RenewResponseAction.Value); context.BindingParameters.Add(new LocalAddressProvider(_localAddress, issueAndRenewFilter)); } ChannelBuilder channelBuilder = new ChannelBuilder(context, true); IChannelFactory innerChannelFactory; // if the underlying transport does not support request/reply, wrap it inside // a service channel factory. if (channelBuilder.CanBuildChannelFactory <IRequestChannel>()) { innerChannelFactory = channelBuilder.BuildChannelFactory <IRequestChannel>(); _requiresManualReplyAddressing = true; } else { ClientRuntime clientRuntime = new ClientRuntime("RequestSecuritySession", NamingHelper.DefaultNamespace); clientRuntime.UseSynchronizationContext = false; clientRuntime.AddTransactionFlowProperties = false; clientRuntime.ValidateMustUnderstand = false; ServiceChannelFactory serviceChannelFactory = ServiceChannelFactory.BuildChannelFactory(channelBuilder, clientRuntime); ClientOperation issueOperation = new ClientOperation(serviceChannelFactory.ClientRuntime, "Issue", IssueAction.Value); issueOperation.Formatter = s_operationFormatter; serviceChannelFactory.ClientRuntime.Operations.Add(issueOperation); ClientOperation renewOperation = new ClientOperation(serviceChannelFactory.ClientRuntime, "Renew", RenewAction.Value); renewOperation.Formatter = s_operationFormatter; serviceChannelFactory.ClientRuntime.Operations.Add(renewOperation); innerChannelFactory = new RequestChannelFactory(serviceChannelFactory); _requiresManualReplyAddressing = false; } SecurityChannelFactory <IAsyncRequestChannel> securityChannelFactory = new SecurityChannelFactory <IAsyncRequestChannel>( securityCapabilities, IssuerBindingContext, channelBuilder, securityProtocolFactory, innerChannelFactory); // attach the ExtendedProtectionPolicy to the securityProtcolFactory so it will be // available when building the channel. if (transportBindingElement != null) { if (securityChannelFactory.SecurityProtocolFactory != null) { securityChannelFactory.SecurityProtocolFactory.ExtendedProtectionPolicy = transportBindingElement.GetProperty <ExtendedProtectionPolicy>(context); } } _rstChannelFactory = securityChannelFactory; MessageVersion = securityChannelFactory.MessageVersion; }
public static OrganizationDetailCollection GetOrganizations(Settings settings) { try { //System.Windows.MessageBox.Show(typeof(GuidList).Assembly.Location); string DiscoveryUrl = string.Format("{0}://{1}:{2}/XRMServices/2011/Discovery.svc", settings.UseSSL ? "https" : "http", settings.UseIFD ? settings.ServerName : settings.UseOffice365 ? "disco." + settings.ServerName : settings.UseOnline ? "dev." + settings.ServerName : settings.ServerName, settings.ServerPort.Length == 0 ? (settings.UseSSL ? 443 : 80) : int.Parse(settings.ServerPort)); string domain = null; string login = settings.Username; ClientCredentials deviceCredentials = null; Uri homeRealm = null; if (!settings.UseWindowsAuth) { if (!settings.UseIFD) { if (!string.IsNullOrEmpty(settings.Domain)) { domain = settings.Domain; //connectionString += string.Format("Domain={0};", settings.Domain); } } string sUsername = settings.Username; if (settings.UseIFD) { if (!string.IsNullOrEmpty(settings.Domain)) { // sUsername = string.Format("{0}\\{1}", settings.Domain, settings.Username); login = string.Format("{0}\\{1}", settings.Domain, settings.Username); } } } if (settings.UseOnline && !settings.UseOffice365) { do { deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ?? DeviceIdManager.RegisterDevice(); } while (deviceCredentials.UserName.Password.Contains(";") || deviceCredentials.UserName.Password.Contains("=") || deviceCredentials.UserName.Password.Contains(" ") || deviceCredentials.UserName.UserName.Contains(";") || deviceCredentials.UserName.UserName.Contains("=") || deviceCredentials.UserName.UserName.Contains(" ")); //connectionString += string.Format("DeviceID={0};DevicePassword={1};", // deviceCredentials.UserName.UserName, // deviceCredentials.UserName.Password); } if (settings.UseIFD && !string.IsNullOrEmpty(settings.HomeRealm)) { //connectionString += string.Format("HomeRealmUri={0};", settings.HomeRealm); homeRealm = new Uri(settings.HomeRealm); } NetworkCredential userCredentials; if (!string.IsNullOrWhiteSpace(domain)) { userCredentials = new NetworkCredential(login, settings.Password, domain); } else if (settings.UseWindowsAuth) { userCredentials = CredentialCache.DefaultNetworkCredentials; } else { userCredentials = new NetworkCredential(login, settings.Password); } if (settings.UseOnline && settings.UseOffice365) { ClientCredentials client = new ClientCredentials(); client.UserName.UserName = login; client.UserName.Password = settings.Password; return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, client, null)); //return CrmServiceClient.DiscoverOrganizations(new Uri("https://disco.crm4.dynamics.com/XRMServices/2011/Discovery.svc"), homeRealm, client, null); } if (deviceCredentials == null) { return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, userCredentials)); } else { return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, null, deviceCredentials)); } // var connection = new CrmServiceClient(settings.GetDiscoveryCrmConnectionString()); //CrmServiceClient.DiscoverOrganizations() // var request = new RetrieveOrganizationsRequest(); // var response = (Microsoft.Xrm.Sdk.Discovery.RetrieveOrganizationsResponse)service.Execute(request); // return connection.DiscoverOrganizations(); } catch (System.IO.FileNotFoundException e) { if (e.Message.Contains("Microsoft.IdentityModel")) { throw new Exception("Unable to load Windows Identity Foundation 3.5. This is a feature that can be enabled on windows 8+ or downloaded for earlier versions -> https://www.microsoft.com/en-nz/download/details.aspx?id=17331 ", e); } else { throw e; } } }
public ManagedTokenDiscoveryServiceProxy(Uri serviceUri, ClientCredentials userCredentials) : base(serviceUri, null, userCredentials, null) { this._proxyManager = new AutoRefreshSecurityToken <DiscoveryServiceProxy, IDiscoveryService>(this); }
/// <summary> /// Initializes a new instance of the CustomSecurityTokenManager class. /// </summary> /// <param name="clientCredentials">The original ClientCredential manager.</param> public CustomSecurityTokenManager(ClientCredentials clientCredentials) : base(clientCredentials) { }
public ManagedTokenOrganizationServiceProxy(Uri serviceUri, ClientCredentials userCredentials) : base(serviceUri, null, userCredentials, null) { this._proxyManager = new AutoRefreshSecurityToken <OrganizationServiceProxy, IOrganizationService>(this); }
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy"></see> class using a organization service URI, home realm URI, and client and device credentials.</summary> /// <param name="deviceCredentials">Type: Returns_ClientCredentials. The Windows Live ID device credentials.</param> /// <param name="homeRealmUri">Type: Returns_URI. This parameter is set to a non-null value when a second ADFS instance is configured as an identity provider to the ADFS instance that pn_CRM_2011 has been configured with for claims authentication. The parameter value is the URI of the WS-Trust metadata endpoint of the second ADFS instance.</param> /// <param name="uri">Type: Returns_URI. The URI of the organization service.</param> /// <param name="clientCredentials">Type: Returns_ClientCredentials. The logon credentials of the client.</param> public AsyncOrganizationServiceProxy(Uri uri, Uri homeRealmUri, ClientCredentials clientCredentials, ClientCredentials deviceCredentials) : base((IServiceConfiguration <IWcfAsyncOrganizationService>) new AsyncOrganizationServiceConfiguration(uri), clientCredentials) { _isAuthenticated.Set(this, false); _homeRealmUri.Set(this, homeRealmUri); _deviceCredentials.Set(this, deviceCredentials); }
public SessionHeader(ClientCredentials credential) { _credentials = credential; }
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy"></see> class using a service configuration and client credentials.</summary> /// <param name="serviceConfiguration">Type: <see cref="T:Microsoft.Xrm.Sdk.Client.IServiceConfiguration`1"></see><<see cref="T:Microsoft.Xrm.Sdk.IOrganizationService"></see>>. A service configuration.</param> /// <param name="clientCredentials">Type: Returns_ClientCredentials. The logon credentials of the client.</param> public AsyncOrganizationServiceProxy(IServiceConfiguration <IWcfAsyncOrganizationService> serviceConfiguration, ClientCredentials clientCredentials) : base(serviceConfiguration, clientCredentials) { }
/// <summary> /// Implement this partial method to configure the service endpoint. /// </summary> /// <param name="serviceEndpoint">The endpoint to configure</param> /// <param name="clientCredentials">The client credentials</param> static void ConfigureEndpoint(ServiceEndpoint serviceEndpoint, ClientCredentials clientCredentials) { throw new NotImplementedException(); }
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy"></see> class using a service configuration and client credentials.</summary> /// <param name="serviceManagement">Type: <see cref="T:Microsoft.Xrm.Sdk.Client.IServiceManagement`1"></see><<see cref="T:Microsoft.Xrm.Sdk.IOrganizationService"></see>>. A service management.</param> /// <param name="clientCredentials">Type: Returns_ClientCredentials. The logon credentials of the client.</param> public AsyncOrganizationServiceProxy(IServiceManagement <IWcfAsyncOrganizationService> serviceManagement, ClientCredentials clientCredentials) : this(serviceManagement as IServiceConfiguration <IWcfAsyncOrganizationService>, clientCredentials) { }
/// <summary> /// Requests a token desribed by an RST. /// </summary> /// <param name="stsAddress">The STS address.</param> /// <param name="binding">The binding.</param> /// <param name="credentials">The credentials.</param> /// <param name="rst">The RST.</param> /// <param name="rstr">The RSTR.</param> /// <returns>A SecurityToken</returns> public static SecurityToken Issue(EndpointAddress stsAddress, Binding binding, ClientCredentials credentials, RequestSecurityToken rst, out RequestSecurityTokenResponse rstr) { var channel = CreateWSTrustChannel( stsAddress, binding, credentials); var token = channel.Issue(rst, out rstr); return(token); }
public RsaSha1RequestAuthenticator(ClientCredentials credentials, AccessToken token, RSAParameters key) : base(credentials, token) { this.key = key; }
/// <summary> /// Creates a new instance. /// </summary> /// <param name="oAuth2TokenEndpoint">End point for getting the OAuth2 token.</param> /// <param name="client">The client credentials for the app/client.</param> /// <param name="bodyContentParamters">Body content parameters</param> internal DineroOauth2Client(Uri oAuth2TokenEndpoint, ClientCredentials client, AuthorizationBodyContent bodyContentParamters) { _oAuth2TokenEndpoint = oAuth2TokenEndpoint; _client = client; _bodyContentParameters = bodyContentParamters; }
public void Should_not_add_rules_for_restricted_machines() { _ruleData.UnitTest_Clear(); SetupSecureEnvironments(); var productionClient = new ClientCredentials { IpAddress = "192.168.0.32" }; var developmentClient = new ClientCredentials { IpAddress = "192.168.2.161" }; var draftRules = _ruleData.UnitTest_GetRuleSet(null, null); var version = draftRules.RuleVersion.Version; var exception = false; try { _ruleData.AddRules( developmentClient, version, new List<RuleDto> { new RuleDto { RuleName = "Test Rule", Machine = "web2", Application = "MyNewApp" } }); } catch { exception = true; } var newRules = _ruleData.UnitTest_GetRuleSet(productionClient, null).RuleVersion.Rules; Assert.IsTrue(exception); Assert.AreEqual(3, newRules.Count); Assert.IsFalse(newRules.Any(r => r.RuleName == "Test Rule")); }