/// <summary>
		/// Initializes a new instance of the <see cref="ExtensionsBindingElement"/> class.
		/// </summary>
		/// <param name="extensionFactory">The extension factory.</param>
		/// <param name="securitySettings">The security settings.</param>
		/// <param name="receiveUnsignedExtensions">Security setting for relying parties.  Should be true for Providers.</param>
		internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings, bool receiveUnsignedExtensions) {
			Requires.NotNull(extensionFactory, "extensionFactory");
			Requires.NotNull(securitySettings, "securitySettings");

			this.ExtensionFactory = extensionFactory;
			this.receiveUnsignedExtensions = receiveUnsignedExtensions;
		}
		public void CanDeserializeSerializedConfiguration()
		{
			SecuritySettings settings = new SecuritySettings();

			AuthorizationRuleProviderData authorizationData1 = new AuthorizationRuleProviderData(authorizationName1);
			authorizationData1.Rules.Add(new AuthorizationRuleData(ruleName11, expression11));
			authorizationData1.Rules.Add(new AuthorizationRuleData(ruleName12, expression12));

			CustomAuthorizationProviderData authorizationData2 = new CustomAuthorizationProviderData(authorizationName2, typeof(MockCustomAuthorizationProvider));

			settings.AuthorizationProviders.Add(authorizationData1);
			settings.AuthorizationProviders.Add(authorizationData2);
			settings.DefaultAuthorizationProviderName = authorizationName1;

			IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
			sections[SecuritySettings.SectionName] = settings;
			IConfigurationSource configurationSource
				= ConfigurationTestHelper.SaveSectionsInFileAndReturnConfigurationSource(sections);

			SecuritySettings roSettigs = (SecuritySettings)configurationSource.GetSection(SecuritySettings.SectionName);

			Assert.IsNotNull(roSettigs);
			Assert.AreEqual(2, roSettigs.AuthorizationProviders.Count);

			Assert.IsNotNull(roSettigs.AuthorizationProviders.Get(authorizationName1));
			Assert.AreSame(typeof(AuthorizationRuleProviderData), roSettigs.AuthorizationProviders.Get(authorizationName1).GetType());
			Assert.AreEqual(2, ((AuthorizationRuleProviderData)roSettigs.AuthorizationProviders.Get(authorizationName1)).Rules.Count);
			Assert.IsNotNull(((AuthorizationRuleProviderData)roSettigs.AuthorizationProviders.Get(authorizationName1)).Rules.Get(ruleName11));
			Assert.AreEqual(expression11, ((AuthorizationRuleProviderData)roSettigs.AuthorizationProviders.Get(authorizationName1)).Rules.Get(ruleName11).Expression);

			Assert.IsNotNull(roSettigs.AuthorizationProviders.Get(authorizationName2));
			Assert.AreSame(typeof(CustomAuthorizationProviderData), roSettigs.AuthorizationProviders.Get(authorizationName2).GetType());
			Assert.AreSame(typeof(MockCustomAuthorizationProvider), ((CustomAuthorizationProviderData)roSettigs.AuthorizationProviders.Get(authorizationName2)).Type);
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="ExtensionsBindingElement"/> class.
		/// </summary>
		/// <param name="extensionFactory">The extension factory.</param>
		/// <param name="securitySettings">The security settings.</param>
		internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings) {
			Contract.Requires<ArgumentNullException>(extensionFactory != null);
			Contract.Requires<ArgumentNullException>(securitySettings != null);

			this.ExtensionFactory = extensionFactory;
			this.relyingPartySecuritySettings = securitySettings as RelyingPartySecuritySettings;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtensionsBindingElement"/> class.
        /// </summary>
        /// <param name="extensionFactory">The extension factory.</param>
        /// <param name="securitySettings">The security settings.</param>
        internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings)
        {
            ErrorUtilities.VerifyArgumentNotNull(extensionFactory, "extensionFactory");
            ErrorUtilities.VerifyArgumentNotNull(securitySettings, "securitySettings");

            this.ExtensionFactory = extensionFactory;
            this.relyingPartySecuritySettings = securitySettings as RelyingPartySecuritySettings;
        }
Example #5
0
		public void SetValue ()
		{
			// SecuritySettings only provides getters - trying SetValue throws
			SecuritySettings ss = new SecuritySettings ();
			Assert.Throws<ArgumentException> (delegate {
				ss.SetValue (SecuritySettings.ElevatedPermissionsProperty, ElevatedPermissions.Required);
			}, "ElevatedPermissionsProperty");
		}
 public void Init()
 {
     securitySettings = new SecuritySettings();
     securitySettings.PasswordHashingIterationCount = 1; // tests will run faster
     configuration = new MembershipRebootConfiguration(securitySettings);
     repository = new FakeUserAccountRepository(); 
     subject = new UserAccountService(configuration, repository);
 }
		/// <summary>
		/// Gets the best association (the one with the longest remaining life) for a given key.
		/// </summary>
		/// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
		/// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
		/// <returns>
		/// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
		/// </returns>
		public Association GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
			var matches = from cryptoKey in this.keyStore.GetKeys(providerEndpoint.AbsoluteUri)
						  where cryptoKey.Value.ExpiresUtc > DateTime.UtcNow
						  orderby cryptoKey.Value.ExpiresUtc descending
						  let assoc = Association.Deserialize(cryptoKey.Key, cryptoKey.Value.ExpiresUtc, cryptoKey.Value.Key)
						  where assoc.HashBitLength >= securityRequirements.MinimumHashBitLength
						  where assoc.HashBitLength <= securityRequirements.MaximumHashBitLength
						  select assoc;
			return matches.FirstOrDefault();
		}
Example #8
0
		internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider)
			: base(messageTypeProvider, InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) {
			Contract.Requires<ArgumentNullException>(tokenManager != null);
			Contract.Requires<ArgumentNullException>(securitySettings != null);
			Contract.Requires<ArgumentNullException>(signingBindingElement != null);
			Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);

			this.TokenManager = tokenManager;
			signingBindingElement.SignatureCallback = this.SignatureCallback;
		}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public SecuritySettings Build()
        {
            securityConfiguration = new SecuritySettings();
            securityConfiguration.DefaultAuthorizationProviderName = (securitySettingsNode.DefaultAuthorizationInstance == null) ? string.Empty : securitySettingsNode.DefaultAuthorizationInstance.Name;
            securityConfiguration.DefaultSecurityCacheProviderName = (securitySettingsNode.DefaultSecurityCacheInstance == null) ? string.Empty : securitySettingsNode.DefaultSecurityCacheInstance.Name;

            BuildAuthorizationProviders();
            BuildSecurityCacheProviders();
			BuildAuthorizationRules();
            return securityConfiguration;
        }
		/// <summary>
		/// Initializes the binding elements for the OAuth channel.
		/// </summary>
		/// <param name="signingBindingElement">The signing binding element.</param>
		/// <param name="store">The nonce store.</param>
		/// <param name="tokenManager">The token manager.</param>
		/// <param name="securitySettings">The security settings.</param>
		/// <returns>
		/// An array of binding elements used to initialize the channel.
		/// </returns>
		private static IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
			Requires.NotNull(securitySettings, "securitySettings");

			var bindingElements = OAuthChannel.InitializeBindingElements(signingBindingElement, store);

			var spTokenManager = tokenManager as IServiceProviderTokenManager;
			var serviceProviderSecuritySettings = securitySettings as ServiceProviderSecuritySettings;
			bindingElements.Insert(0, new TokenHandlingBindingElement(spTokenManager, serviceProviderSecuritySettings));

			return bindingElements.ToArray();
		}
Example #11
0
		protected OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
			: base(messageTypeProvider, bindingElements) {
			Requires.NotNull(tokenManager, "tokenManager");
			Requires.NotNull(securitySettings, "securitySettings");
			Requires.NotNull(signingBindingElement, "signingBindingElement");
			Requires.That(signingBindingElement.SignatureCallback == null, "signingBindingElement", OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
			Requires.NotNull(bindingElements, "bindingElements");

			this.TokenManager = tokenManager;
			signingBindingElement.SignatureCallback = this.SignatureCallback;
		}
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            // parse "security" section
            XmlNode nodeSecurity = section.SelectSingleNode("security");
            if (nodeSecurity == null)
                throw new Exception("'websitepanel/security' section is missing");

            security = new SecuritySettings();
            security.ParseSection(nodeSecurity);

            return null;
        }
 public void TestDefaults()
 {
     var settings = new SecuritySettings();
     Assert.AreEqual(false, settings.MultiTenant);
     Assert.AreEqual("default", settings.DefaultTenant);
     Assert.AreEqual(false, settings.EmailIsUsername);
     Assert.AreEqual(false, settings.UsernamesUniqueAcrossTenants);
     Assert.AreEqual(true, settings.RequireAccountVerification);
     Assert.AreEqual(true, settings.AllowLoginAfterAccountCreation);
     Assert.AreEqual(10, settings.AccountLockoutFailedLoginAttempts);
     Assert.AreEqual(TimeSpan.FromMinutes(5), settings.AccountLockoutDuration);
     Assert.AreEqual(true, settings.AllowAccountDeletion);
 }
        public void AuthorizationCollection()
        {
            SecuritySettings settings = new SecuritySettings();

            AuthorizationProviderDataCollection authProviders = new AuthorizationProviderDataCollection();
            CustomAuthorizationProviderData data = new CustomAuthorizationProviderData();
            data.Name = "name";
            authProviders.Add(data);
            foreach (AuthorizationProviderData providerData in authProviders)
            {
                settings.AuthorizationProviders.Add(providerData);
            }
            Assert.AreEqual(settings.AuthorizationProviders.Count, 1);
        }
Example #15
0
 /// <summary>
 /// <para>Initialize a new instance of the <see cref="SecuritySettingsNode"/> class with a <see cref="SecuritySettings"/> object.</para>
 /// </summary>
 /// <param name="securitySettings">
 /// <para>The <see cref="SecuritySettings"/> runtime configuration.</para>
 /// </param>
 public SecuritySettingsNode(SecuritySettings securitySettings)
     : base()
 {
     if (securitySettings == null)
     {
         throw new ArgumentNullException("securitySettings");
     }
     this.securitySettings = securitySettings;
     this.onAuthenticationProviderRemoved += new ConfigurationNodeChangedEventHandler(OnAuthenticationDefaultProviderRemoved);
     this.onAuthorizationProviderRemoved += new ConfigurationNodeChangedEventHandler(OnAuthorizationDefaultProviderRemoved);
     this.onProfileProviderRemoved += new ConfigurationNodeChangedEventHandler(OnProfileDefaultProviderRemoved);
     this.onRolesProviderRemoved += new ConfigurationNodeChangedEventHandler(OnRolesDefaultProviderRemoved);
     this.onSecurityCacheProviderRemoved += new ConfigurationNodeChangedEventHandler(OnSecurityCacheDefaultProviderRemoved);
 }
Example #16
0
        public PayByPhoneApi()
        {
            _myWebClient = new CookieWebClient();
            _myWebClient.BaseAddress = "https://m.paybyphone.com";
            _myWebClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            _myWebClient.Headers[HttpRequestHeader.UserAgent] = Api.UserAgent;
            _myWebClient.Headers["Origin"] = "https://m.paybyphone.com";

            _myVehicleManager = new VehicleManager(this);
            _myPaymentDetails = new PaymentDetails(this);
            _myEmailSettings = new EmailSettings(this);
            _mySecuritySettings = new SecuritySettings(this);
            _myTermsConditions = new TermsConditions(this);
            _myLocationManager = new LocationManager(this);
        }
 public void TestDefaults()
 {
     var settings = new SecuritySettings();
     Assert.AreEqual("MembershipReboot", settings.ConnectionStringName);
     Assert.AreEqual(false, settings.MultiTenant);
     Assert.AreEqual("default", settings.DefaultTenant);
     Assert.AreEqual(false, settings.EmailIsUsername);
     Assert.AreEqual(false, settings.UsernamesUniqueAcrossTenants);
     Assert.AreEqual(true, settings.RequireAccountVerification);
     Assert.AreEqual(true, settings.AllowLoginAfterAccountCreation);
     Assert.AreEqual(10, settings.AccountLockoutFailedLoginAttempts);
     Assert.AreEqual(TimeSpan.FromMinutes(5), settings.AccountLockoutDuration);
     Assert.AreEqual(true, settings.AllowAccountDeletion);
     Assert.AreEqual(0, settings.PasswordHashingIterationCount);
     Assert.AreEqual(0, settings.PasswordResetFrequency);
 }
		/// <summary>
		/// Creates an association request message that is appropriate for a given Provider.
		/// </summary>
		/// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
		/// <param name="provider">The provider to create an association with.</param>
		/// <returns>
		/// The message to send to the Provider to request an association.
		/// Null if no association could be created that meet the security requirements
		/// and the provider OpenID version.
		/// </returns>
		internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider) {
			Requires.NotNull(securityRequirements, "securityRequirements");
			Requires.NotNull(provider, "provider");

			// Apply our knowledge of the endpoint's transport, OpenID version, and
			// security requirements to decide the best association.
			bool unencryptedAllowed = provider.Uri.IsTransportSecure();
			bool useDiffieHellman = !unencryptedAllowed;
			string associationType, sessionType;
			if (!HmacShaAssociation.TryFindBestAssociation(Protocol.Lookup(provider.Version), true, securityRequirements, useDiffieHellman, out associationType, out sessionType)) {
				// There are no associations that meet all requirements.
				Logger.OpenId.Warn("Security requirements and protocol combination knock out all possible association types.  Dumb mode forced.");
				return null;
			}

			return Create(securityRequirements, provider, associationType, sessionType);
		}
        public void CanDeserializeSerializedConfiguration()
        {
            SecuritySettings settings = new SecuritySettings();

            CustomSecurityCacheProviderData securityCacheData1 = new CustomSecurityCacheProviderData(securityCacheName1, typeof(MockCustomSecurityCacheProvider));

            settings.SecurityCacheProviders.Add(securityCacheData1);
            settings.DefaultSecurityCacheProviderName = securityCacheName1;

            IDictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
            sections[SecuritySettings.SectionName] = settings;
            IConfigurationSource configurationSource
                = ConfigurationTestHelper.SaveSectionsInFileAndReturnConfigurationSource(sections);

            SecuritySettings roSettigs = (SecuritySettings)configurationSource.GetSection(SecuritySettings.SectionName);

            Assert.IsNotNull(roSettigs);
            Assert.AreEqual(1, roSettigs.SecurityCacheProviders.Count);

            Assert.IsNotNull(roSettigs.SecurityCacheProviders.Get(securityCacheName1));
            Assert.AreSame(typeof(CustomSecurityCacheProviderData), roSettigs.SecurityCacheProviders.Get(securityCacheName1).GetType());
            Assert.AreSame(typeof(MockCustomSecurityCacheProvider), ((CustomSecurityCacheProviderData)roSettigs.SecurityCacheProviders.Get(securityCacheName1)).Type);
        }
		/// <summary>
		/// Creates an association request message that is appropriate for a given Provider.
		/// </summary>
		/// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
		/// <param name="provider">The provider to create an association with.</param>
		/// <param name="associationType">Type of the association.</param>
		/// <param name="sessionType">Type of the session.</param>
		/// <returns>
		/// The message to send to the Provider to request an association.
		/// Null if no association could be created that meet the security requirements
		/// and the provider OpenID version.
		/// </returns>
		internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider, string associationType, string sessionType) {
			Requires.NotNull(securityRequirements, "securityRequirements");
			Requires.NotNull(provider, "provider");
			Requires.NotNullOrEmpty(associationType, "associationType");
			Requires.NotNull(sessionType, "sessionType");

			bool unencryptedAllowed = provider.Uri.IsTransportSecure();
			if (unencryptedAllowed) {
				var associateRequest = new AssociateUnencryptedRequest(provider.Version, provider.Uri);
				associateRequest.AssociationType = associationType;
				return associateRequest;
			} else {
				if (OpenIdUtilities.IsDiffieHellmanPresent) {
					var associateRequest = new AssociateDiffieHellmanRequest(provider.Version, provider.Uri);
					associateRequest.AssociationType = associationType;
					associateRequest.SessionType = sessionType;
					associateRequest.InitializeRequest();
					return associateRequest;
				} else {
					return null;
				}
			}
		}
Example #21
0
        /// <summary>
        /// Creates an association request message that is appropriate for a given Provider.
        /// </summary>
        /// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
        /// <param name="provider">The provider to create an association with.</param>
        /// <param name="associationType">Type of the association.</param>
        /// <param name="sessionType">Type of the session.</param>
        /// <returns>
        /// The message to send to the Provider to request an association.
        /// Null if no association could be created that meet the security requirements
        /// and the provider OpenID version.
        /// </returns>
        internal static AssociateRequest Create(SecuritySettings securityRequirements, ProviderEndpointDescription provider, string associationType, string sessionType)
        {
            ErrorUtilities.VerifyArgumentNotNull(securityRequirements, "securityRequirements");
            ErrorUtilities.VerifyArgumentNotNull(provider, "provider");
            ErrorUtilities.VerifyNonZeroLength(associationType, "associationType");
            ErrorUtilities.VerifyArgumentNotNull(sessionType, "sessionType");

            bool unencryptedAllowed = provider.Endpoint.IsTransportSecure();
            if (unencryptedAllowed) {
                var associateRequest = new AssociateUnencryptedRequest(provider.ProtocolVersion, provider.Endpoint);
                associateRequest.AssociationType = associationType;
                return associateRequest;
            } else {
                var associateRequest = new AssociateDiffieHellmanRequest(provider.ProtocolVersion, provider.Endpoint);
                associateRequest.AssociationType = associationType;
                associateRequest.SessionType = sessionType;
                associateRequest.InitializeRequest();
                return associateRequest;
            }
        }
 public IpAddressValidationMiddleware(RequestDelegate next, SecuritySettings securitySettings)
 {
     _next             = next;
     _securitySettings = securitySettings;
 }
		/// <summary>
		/// Gets the best association (the one with the longest remaining life) for a given key.
		/// </summary>
		/// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
		/// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
		/// <returns>
		/// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
		/// </returns>
		/// <remarks>
		/// In the event that multiple associations exist for the given
		/// <paramref name="providerEndpoint"/>, it is important for the
		/// implementation for this method to use the <paramref name="securityRequirements"/>
		/// to pick the best (highest grade or longest living as the host's policy may dictate)
		/// association that fits the security requirements.
		/// Associations that are returned that do not meet the security requirements will be
		/// ignored and a new association created.
		/// </remarks>
		Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
			Contract.Requires<ArgumentNullException>(providerEndpoint != null);
			Contract.Requires<ArgumentNullException>(securityRequirements != null);
			throw new NotImplementedException();
		}
 public GeneralConfiguration(SecuritySettings securitySettings)
 {
     _securitySettings = securitySettings;
 }
Example #25
0
 public StoreService(IRepository <Store> storeRepository, IEventPublisher eventPublisher, SecuritySettings securitySettings, IRepository <StoreBannerImage> storeBannerImageRepository)
 {
     _storeRepository            = storeRepository;
     _eventPublisher             = eventPublisher;
     _securitySettings           = securitySettings;
     _storeBannerImageRepository = storeBannerImageRepository;
 }
        public new void SetUp()
        {
            _customerSettings = new CustomerSettings();
            _securitySettings = new SecuritySettings()
            {
                EncryptionKey = "273ece6f97dd844d"
            };
            _rewardPointsSettings = new RewardPointsSettings()
            {
                Enabled = false,
            };

            _encryptionService = new EncryptionService(_securitySettings);
            _customerRepo      = MockRepository.GenerateMock <IRepository <Customer> >();
            var customer1 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Hashed,
                Active         = true
            };

            string saltKey  = _encryptionService.CreateSaltKey(5);
            string password = _encryptionService.CreatePasswordHash("password", saltKey);

            customer1.PasswordSalt = saltKey;
            customer1.Password     = password;
            AddCustomerToRegisteredRole(customer1);

            var customer2 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer2);

            var customer3 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Encrypted,
                Password       = _encryptionService.EncryptText("password"),
                Active         = true
            };

            AddCustomerToRegisteredRole(customer3);

            var customer4 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer4);

            var customer5 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            _eventPublisher = MockRepository.GenerateMock <IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg <object> .Is.Anything));

            _customerRepo.Expect(x => x.Table).Return(new List <Customer>()
            {
                customer1, customer2, customer3, customer4, customer5
            }.AsQueryable());

            _customerRoleRepo        = MockRepository.GenerateMock <IRepository <CustomerRole> >();
            _genericAttributeRepo    = MockRepository.GenerateMock <IRepository <GenericAttribute> >();
            _rewardPointsHistoryRepo = MockRepository.GenerateMock <IRepository <RewardPointsHistory> >();
            _userAgent = MockRepository.GenerateMock <IUserAgent>();

            _genericAttributeService       = MockRepository.GenerateMock <IGenericAttributeService>();
            _newsLetterSubscriptionService = MockRepository.GenerateMock <INewsLetterSubscriptionService>();

            _storeContext = MockRepository.GenerateMock <IStoreContext>();

            _services = MockRepository.GenerateMock <ICommonServices>();
            _services.Expect(x => x.StoreContext).Return(_storeContext);
            _services.Expect(x => x.RequestCache).Return(NullRequestCache.Instance);
            _services.Expect(x => x.Cache).Return(NullCache.Instance);
            _services.Expect(x => x.EventPublisher).Return(_eventPublisher);

            _messageModelProvider = MockRepository.GenerateMock <Lazy <IMessageModelProvider> >();
            _gdprTool             = MockRepository.GenerateMock <Lazy <IGdprTool> >();

            _customerService = new CustomerService(
                _customerRepo,
                _customerRoleRepo,
                _genericAttributeRepo,
                _rewardPointsHistoryRepo,
                _genericAttributeService,
                _rewardPointsSettings,
                _services,
                new FakeHttpContext("~/"),
                _userAgent,
                new CustomerSettings(),
                _messageModelProvider,
                _gdprTool);

            _customerRegistrationService = new CustomerRegistrationService(_customerService,
                                                                           _encryptionService, _newsLetterSubscriptionService, _rewardPointsSettings, _customerSettings, _storeContext, _eventPublisher);
        }
Example #27
0
 public ConfigureMemberIdentityOptions(IOptions <MemberPasswordConfigurationSettings> memberPasswordConfiguration, IOptions <SecuritySettings> securitySettings)
 {
     _memberPasswordConfiguration = memberPasswordConfiguration.Value;
     _securitySettings            = securitySettings.Value;
 }
Example #28
0
 public SecurityService(IOptions <SecuritySettings> options)
 {
     _securitySettings = options.Value;
 }
 public SmiRedirectResultExecutor(ILoggerFactory loggerFactory,
                                  IUrlHelperFactory urlHelperFactory,
                                  SecuritySettings securitySettings) : base(loggerFactory, urlHelperFactory)
 {
     _securitySettings = securitySettings;
 }
        /// <summary>
        /// <para>Gets the name of the default <see cref="AuthorizationProviderData"/>.</para>
        /// </summary>
        /// <returns>
        /// <para>The name of the default <see cref="AuthorizationProviderData"/>.</para>
        /// </returns>
        public string GetDefaultAuthorizationProviderName()
        {
            SecuritySettings settings = GetSecuritySettings();

            return(settings.DefaultAuthorizationProviderName);
        }
        /// <summary>
        /// <para>Gets the name of the default <see cref="SecurityCacheProviderData"/>.</para>
        /// </summary>
        /// <returns>
        /// <para>The name of the default <see cref="SecurityCacheProviderData"/>.</para>
        /// </returns>
        public string GetDefaultSecurityCacheProviderName()
        {
            SecuritySettings settings = GetSecuritySettings();

            return(settings.DefaultSecurityCacheProviderName);
        }
Example #32
0
 public CustomerWebService(
     IExternalAuthenticationService externalAuthenticationService,
     ICustomerAttributeParser customerAttributeParser,
     ICustomerAttributeService customerAttributeService,
     ILocalizationService localizationService,
     IDateTimeHelper dateTimeHelper,
     INewsLetterSubscriptionService newsLetterSubscriptionService,
     IWorkContext workContext,
     IStoreContext storeContext,
     ICountryService countryService,
     IStateProvinceService stateProvinceService,
     IGenericAttributeService genericAttributeService,
     IWorkflowMessageService workflowMessageService,
     IReturnRequestService returnRequestService,
     IStoreMappingService storeMappingService,
     IAddressWebService addressWebService,
     IOrderService orderService,
     IDownloadService downloadService,
     IPictureService pictureService,
     IProductService productService,
     IAuctionService auctionService,
     CustomerSettings customerSettings,
     DateTimeSettings dateTimeSettings,
     TaxSettings taxSettings,
     ForumSettings forumSettings,
     ExternalAuthenticationSettings externalAuthenticationSettings,
     SecuritySettings securitySettings,
     CaptchaSettings captchaSettings,
     RewardPointsSettings rewardPointsSettings,
     OrderSettings orderSettings,
     MediaSettings mediaSettings,
     VendorSettings vendorSettings
     )
 {
     this._externalAuthenticationService = externalAuthenticationService;
     this._customerAttributeParser       = customerAttributeParser;
     this._customerAttributeService      = customerAttributeService;
     this._localizationService           = localizationService;
     this._dateTimeHelper = dateTimeHelper;
     this._newsLetterSubscriptionService = newsLetterSubscriptionService;
     this._workContext                    = workContext;
     this._storeContext                   = storeContext;
     this._countryService                 = countryService;
     this._stateProvinceService           = stateProvinceService;
     this._genericAttributeService        = genericAttributeService;
     this._workflowMessageService         = workflowMessageService;
     this._returnRequestService           = returnRequestService;
     this._storeMappingService            = storeMappingService;
     this._addressWebService              = addressWebService;
     this._orderService                   = orderService;
     this._downloadService                = downloadService;
     this._pictureService                 = pictureService;
     this._productService                 = productService;
     this._auctionService                 = auctionService;
     this._customerSettings               = customerSettings;
     this._dateTimeSettings               = dateTimeSettings;
     this._taxSettings                    = taxSettings;
     this._forumSettings                  = forumSettings;
     this._externalAuthenticationSettings = externalAuthenticationSettings;
     this._securitySettings               = securitySettings;
     this._captchaSettings                = captchaSettings;
     this._rewardPointsSettings           = rewardPointsSettings;
     this._orderSettings                  = orderSettings;
     this._mediaSettings                  = mediaSettings;
     this._vendorSettings                 = vendorSettings;
 }
 public TokenProvider(IOptions <SecuritySettings> securitySettings)
 {
     _securitySettings = securitySettings.Value;
 }
 /// <summary>
 /// Gets the best association (the one with the longest remaining life) for a given key.
 /// </summary>
 /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
 /// <param name="securitySettings">The security settings.</param>
 /// <returns>
 /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
 /// </returns>
 public Association GetAssociation(Uri distinguishingFactor, SecuritySettings securitySettings)
 {
     return this.associationStore.GetAssociation(distinguishingFactor, securitySettings);
 }
Example #35
0
 public GoogleRecaptchaMiddleware(RequestDelegate next, SecuritySettings securitySettings)
 {
     _next             = next;
     _securitySettings = securitySettings;
     _accessRegister   = new IpAddressAccessRegister();
 }
Example #36
0
 public EncryptionService(SecuritySettings securitySettings)
 {
     this._securitySettings = securitySettings;
 }
Example #37
0
 public WebHelper(HttpContextBase httpContext,
                  SecuritySettings securitySettings)
 {
     _httpContext      = httpContext;
     _securitySettings = securitySettings;
 }
Example #38
0
 public CustomerModelFactory(IAddressModelFactory addressModelFactory,
                             IDateTimeHelper dateTimeHelper,
                             DateTimeSettings dateTimeSettings,
                             TaxSettings taxSettings,
                             ILocalizationService localizationService,
                             IWorkContext workContext,
                             IStoreContext storeContext,
                             IStoreMappingService storeMappingService,
                             ICustomerAttributeParser customerAttributeParser,
                             ICustomerAttributeService customerAttributeService,
                             IGenericAttributeService genericAttributeService,
                             RewardPointsSettings rewardPointsSettings,
                             CustomerSettings customerSettings,
                             AddressSettings addressSettings,
                             ForumSettings forumSettings,
                             SubscriptionSettings subscriptionSettings,
                             ICountryService countryService,
                             IStateProvinceService stateProvinceService,
                             ISubscriptionService subscriptionService,
                             IPictureService pictureService,
                             INewsLetterSubscriptionService newsLetterSubscriptionService,
                             IOpenAuthenticationService openAuthenticationService,
                             IDownloadService downloadService,
                             IReturnRequestService returnRequestService,
                             MediaSettings mediaSettings,
                             CaptchaSettings captchaSettings,
                             SecuritySettings securitySettings,
                             ExternalAuthenticationSettings externalAuthenticationSettings,
                             CatalogSettings catalogSettings,
                             ContributorSettings contributorSettings)
 {
     this._addressModelFactory            = addressModelFactory;
     this._dateTimeHelper                 = dateTimeHelper;
     this._dateTimeSettings               = dateTimeSettings;
     this._taxSettings                    = taxSettings;
     this._localizationService            = localizationService;
     this._workContext                    = workContext;
     this._storeContext                   = storeContext;
     this._storeMappingService            = storeMappingService;
     this._customerAttributeParser        = customerAttributeParser;
     this._customerAttributeService       = customerAttributeService;
     this._genericAttributeService        = genericAttributeService;
     this._rewardPointsSettings           = rewardPointsSettings;
     this._customerSettings               = customerSettings;
     this._addressSettings                = addressSettings;
     this._forumSettings                  = forumSettings;
     this._subscriptionSettings           = subscriptionSettings;
     this._countryService                 = countryService;
     this._stateProvinceService           = stateProvinceService;
     this._subscriptionService            = subscriptionService;
     this._pictureService                 = pictureService;
     this._newsLetterSubscriptionService  = newsLetterSubscriptionService;
     this._openAuthenticationService      = openAuthenticationService;
     this._downloadService                = downloadService;
     this._returnRequestService           = returnRequestService;
     this._mediaSettings                  = mediaSettings;
     this._captchaSettings                = captchaSettings;
     this._securitySettings               = securitySettings;
     this._externalAuthenticationSettings = externalAuthenticationSettings;
     this._catalogSettings                = catalogSettings;
     this._contributorSettings            = contributorSettings;
 }
 public AuthenticationConfiguration(SecuritySettings securitySettings)
 {
     _securitySettings = securitySettings;
 }
Example #40
0
        private static IChannelBindingElement[] InitializeBindingElements <T>(IAssociationStore <T> associationStore, INonceStore nonceStore, SecuritySettings securitySettings, bool nonVerifying)
        {
            Contract.Requires <ArgumentNullException>(securitySettings != null);
            Contract.Requires <ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings);

            var rpSecuritySettings = securitySettings as RelyingPartySecuritySettings;
            var opSecuritySettings = securitySettings as ProviderSecuritySettings;

            ErrorUtilities.VerifyInternal(rpSecuritySettings != null || opSecuritySettings != null, "Expected an RP or OP security settings instance.");
            ErrorUtilities.VerifyInternal(!nonVerifying || rpSecuritySettings != null, "Non-verifying channels can only be constructed for relying parties.");
            bool isRelyingPartyRole = rpSecuritySettings != null;

            var rpAssociationStore = associationStore as IAssociationStore <Uri>;
            var opAssociationStore = associationStore as IAssociationStore <AssociationRelyingPartyType>;

            ErrorUtilities.VerifyInternal(isRelyingPartyRole || opAssociationStore != null, "Providers MUST have an association store.");

            SigningBindingElement signingElement;

            if (isRelyingPartyRole)
            {
                signingElement = nonVerifying ? null : new SigningBindingElement(rpAssociationStore);
            }
            else
            {
                signingElement = new SigningBindingElement(opAssociationStore, opSecuritySettings);
            }

            var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();

            List <IChannelBindingElement> elements = new List <IChannelBindingElement>(8);

            elements.Add(new ExtensionsBindingElement(extensionFactory, securitySettings));
            if (isRelyingPartyRole)
            {
                elements.Add(new RelyingPartySecurityOptions(rpSecuritySettings));
                elements.Add(new BackwardCompatibilityBindingElement());
                ReturnToNonceBindingElement requestNonceElement = null;

                if (associationStore != null)
                {
                    if (nonceStore != null)
                    {
                        // There is no point in having a ReturnToNonceBindingElement without
                        // a ReturnToSignatureBindingElement because the nonce could be
                        // artificially changed without it.
                        requestNonceElement = new ReturnToNonceBindingElement(nonceStore, rpSecuritySettings);
                        elements.Add(requestNonceElement);
                    }

                    // It is important that the return_to signing element comes last
                    // so that the nonce is included in the signature.
                    elements.Add(new ReturnToSignatureBindingElement(rpAssociationStore, rpSecuritySettings));
                }

                ErrorUtilities.VerifyOperation(!rpSecuritySettings.RejectUnsolicitedAssertions || requestNonceElement != null, OpenIdStrings.UnsolicitedAssertionRejectionRequiresNonceStore);
            }
            else
            {
                // Providers must always have a nonce store.
                ErrorUtilities.VerifyArgumentNotNull(nonceStore, "nonceStore");
            }

            if (nonVerifying)
            {
                elements.Add(new SkipSecurityBindingElement());
            }
            else
            {
                if (nonceStore != null)
                {
                    elements.Add(new StandardReplayProtectionBindingElement(nonceStore, true));
                }

                elements.Add(new StandardExpirationBindingElement());
                elements.Add(signingElement);
            }

            return(elements.ToArray());
        }
Example #41
0
 public JwtService(IOptions <ApplicationSettings> options)
 {
     this.securitySettings = options.Value.Security;
 }
Example #42
0
        private static void CheckAndMergeStores()
        {
            SecuritySettings securitySettings = (SecuritySettings)ConfigurationManager.GetSection(SecuritySettings.SectionName);

            NameTypeConfigurationElementCollection <AuthorizationProviderData, CustomAuthorizationProviderData> providerElementCollection = securitySettings.AuthorizationProviders;

            LogEntry entry = new LogEntry();

            entry.Severity = TraceEventType.Verbose;
            entry.Priority = -1;

            if (Logger.ShouldLog(entry))
            {
                entry.Message = "Checking for authorization store merge files...";
                Logger.Write(entry);
            }

            for (int i = 0; i < providerElementCollection.Count; i++)
            {
                AuthorizationProviderData providerData = providerElementCollection.Get(i);

                string toStoreLocation = providerData.ElementInformation.Properties["storeLocation"].Value as string;
                toStoreLocation = toStoreLocation.Replace("{currentPath}", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                string toFileName = toStoreLocation.Replace("msxml://", "");

                string fromFileName      = Path.Combine(Path.Combine(Path.GetDirectoryName(toFileName), AZ_MERGE_FOLDER), Path.GetFileName(toFileName));
                string fromStoreLocation = string.Format("msxml://{0}", fromFileName);

                if (File.Exists(fromFileName))
                {
                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = string.Format("Found merge file \"{0}\".", fromFileName);
                        Logger.Write(entry);
                    }

                    string backupFileName = Path.ChangeExtension(toFileName, "bak");

                    int counter = 0;

                    while (File.Exists(backupFileName))
                    {
                        counter++;
                        backupFileName = Path.ChangeExtension(backupFileName, string.Format("bak{0}", counter));
                    }

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = string.Format("Creating backup \"{0}\"...", backupFileName);
                        Logger.Write(entry);
                    }

                    File.Copy(toFileName, backupFileName);

                    FileInfo fi = new FileInfo(toFileName);
                    fi.IsReadOnly = false;

                    MergeStores(fromStoreLocation, toStoreLocation);

                    string mergedFileName = Path.ChangeExtension(fromFileName, "merged");

                    counter = 0;

                    while (File.Exists(mergedFileName))
                    {
                        counter++;
                        mergedFileName = Path.ChangeExtension(mergedFileName, string.Format("merged{0}", counter));
                    }

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = string.Format("Renaming merge file to \"{0}\"...", mergedFileName);
                        Logger.Write(entry);
                    }

                    File.Move(fromFileName, mergedFileName);

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = string.Format("Merge complete.");
                        Logger.Write(entry);
                    }
                }
            }
        }
 public void ConstructorTest()
 {
     SecuritySettings data = new SecuritySettings();
     Assert.IsNotNull(data.AuthenticationProviders);
     Assert.AreEqual(0, data.AuthenticationProviders.Count);
 }
 public EnvController(SecuritySettings securitySettings)
 {
     _securitySettings = securitySettings;
 }
 public ConnectionAccountant(IUserRegistrationService userRegistrationService, IConnectedAccountService connectedAccountService, SecuritySettings securitySettings, IUserService userService, UserSettings userSettings, IRoleService roleService)
 {
     _userRegistrationService = userRegistrationService;
     _connectedAccountService = connectedAccountService;
     _securitySettings        = securitySettings;
     _userService             = userService;
     _userSettings            = userSettings;
     _roleService             = roleService;
 }
Example #46
0
 public AppSettingsController(IAppSettingsService appSettingsService, IUserService userService, IOptions <SecuritySettings> securitySettings)
 {
     this.appSettingsService = appSettingsService;
     this.userService        = userService;
     this.securitySettings   = securitySettings.Value;
 }
Example #47
0
        public new void SetUp()
        {
            _customerSettings = new CustomerSettings();
            _securitySettings = new SecuritySettings()
            {
                EncryptionKey = "273ece6f97dd844d"
            };
            _rewardPointsSettings = new RewardPointsSettings()
            {
                Enabled = false,
            };

            _encryptionService = new EncryptionService(_securitySettings);
            _customerRepo      = MockRepository.GenerateMock <IRepository <Customer> >();
            var customer1 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Hashed,
                Active         = true
            };

            string saltKey  = _encryptionService.CreateSaltKey(5);
            string password = _encryptionService.CreatePasswordHash("password", saltKey);

            customer1.PasswordSalt = saltKey;
            customer1.Password     = password;
            AddCustomerToRegisteredRole(customer1);

            var customer2 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer2);

            var customer3 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Encrypted,
                Password       = _encryptionService.EncryptText("password"),
                Active         = true
            };

            AddCustomerToRegisteredRole(customer3);

            var customer4 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer4);

            var customer5 = new Customer()
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            _eventPublisher = MockRepository.GenerateMock <IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg <object> .Is.Anything));

            _customerRepo.Expect(x => x.Table).Return(new List <Customer>()
            {
                customer1, customer2, customer3, customer4, customer5
            }.AsQueryable());

            _customerRoleRepo     = MockRepository.GenerateMock <IRepository <CustomerRole> >();
            _genericAttributeRepo = MockRepository.GenerateMock <IRepository <GenericAttribute> >();
            _orderRepo            = MockRepository.GenerateMock <IRepository <Order> >();
            _forumPostRepo        = MockRepository.GenerateMock <IRepository <ForumPost> >();
            _forumTopicRepo       = MockRepository.GenerateMock <IRepository <ForumTopic> >();

            _genericAttributeService       = MockRepository.GenerateMock <IGenericAttributeService>();
            _newsLetterSubscriptionService = MockRepository.GenerateMock <INewsLetterSubscriptionService>();

            _localizationService = MockRepository.GenerateMock <ILocalizationService>();
            _customerService     = new CustomerService(new NopNullCache(), _customerRepo, _customerRoleRepo,
                                                       _genericAttributeRepo, _orderRepo, _forumPostRepo, _forumTopicRepo,
                                                       null, null, null, null, null,
                                                       _genericAttributeService, _eventPublisher, _customerSettings);
            _customerRegistrationService = new CustomerRegistrationService(_customerService,
                                                                           _encryptionService, _newsLetterSubscriptionService, _localizationService,
                                                                           _rewardPointsSettings, _customerSettings);
        }
 public ValidateIpAddressFilter(IWebHelper webHelper,
                                SecuritySettings securitySettings)
 {
     _webHelper        = webHelper;
     _securitySettings = securitySettings;
 }
Example #49
0
 /// <summary>
 /// Determines whether the document can be saved.
 /// </summary>
 public bool CanSave(ref string message) => !SecuritySettings.CanSave(ref message) ? false : true;
Example #50
0
		/// <summary>
		/// Creates an association request message that is appropriate for a given Provider.
		/// </summary>
		/// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
		/// <param name="provider">The provider to create an association with.</param>
		/// <param name="associationType">Type of the association.</param>
		/// <param name="sessionType">Type of the session.</param>
		/// <returns>
		/// The message to send to the Provider to request an association.
		/// Null if no association could be created that meet the security requirements
		/// and the provider OpenID version.
		/// </returns>
		internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider, string associationType, string sessionType) {
			Contract.Requires<ArgumentNullException>(securityRequirements != null);
			Contract.Requires<ArgumentNullException>(provider != null);
			Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
			Contract.Requires<ArgumentNullException>(sessionType != null);

			bool unencryptedAllowed = provider.Uri.IsTransportSecure();
			if (unencryptedAllowed) {
				var associateRequest = new AssociateUnencryptedRequest(provider.Version, provider.Uri);
				associateRequest.AssociationType = associationType;
				return associateRequest;
			} else {
				var associateRequest = new AssociateDiffieHellmanRequest(provider.Version, provider.Uri);
				associateRequest.AssociationType = associationType;
				associateRequest.SessionType = sessionType;
				associateRequest.InitializeRequest();
				return associateRequest;
			}
		}
        /// <summary>
        /// <para>Gets the name of the default <see cref="RolesProviderData"/>.</para>
        /// </summary>
        /// <returns>
        /// <para>The name of the default <see cref="RolesProviderData"/>.</para>
        /// </returns>
        public virtual string GetDefaultRoleProviderName()
        {
            SecuritySettings settings = GetSecuritySettings();

            return(settings.DefaultRolesProviderName);
        }
 public LoginService(ApiContext dbContext, IOptions <SecuritySettings> securitySettings)
 {
     this._dbContext        = dbContext;
     this._securitySettings = securitySettings.Value;
 }
        /// <summary>
        /// <para>Gets the name of the default <see cref="AuthenticationProviderData"/>.</para>
        /// </summary>
        /// <returns>
        /// <para>The name of the default <see cref="AuthenticationProviderData"/>.</para>
        /// </returns>
        public virtual string GetDefaultAuthenticationProviderName()
        {
            SecuritySettings settings = GetSecuritySettings();

            return(settings.DefaultAuthenticationProviderName);
        }
Example #54
0
        /// <summary>
        /// Initializes the binding elements for the OAuth channel.
        /// </summary>
        /// <param name="signingBindingElement">The signing binding element.</param>
        /// <param name="store">The nonce store.</param>
        /// <param name="tokenManager">The token manager.</param>
        /// <param name="securitySettings">The security settings.</param>
        /// <returns>
        /// An array of binding elements used to initialize the channel.
        /// </returns>
        private static IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings)
        {
            Requires.NotNull(securitySettings, "securitySettings");

            var bindingElements = OAuthChannel.InitializeBindingElements(signingBindingElement, store);

            var spTokenManager = tokenManager as IServiceProviderTokenManager;
            var serviceProviderSecuritySettings = securitySettings as ServiceProviderSecuritySettings;

            bindingElements.Insert(0, new TokenHandlingBindingElement(spTokenManager, serviceProviderSecuritySettings));

            return(bindingElements.ToArray());
        }
Example #55
0
 public AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService, SecuritySettings securitySettings)
 {
     _ignoreFilter      = ignoreFilter;
     _permissionService = permissionService;
     _securitySettings  = securitySettings;
 }
Example #56
0
 public void ConstructorTest()
 {
     SecuritySettings settings = new SecuritySettings();
     Assert.IsNotNull(settings.RolesProviders);
     Assert.AreEqual(0, settings.RolesProviders.Count);
 }
 /// <summary>
 /// Gets the best association (the one with the longest remaining life) for a given key.
 /// </summary>
 /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
 /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
 /// <returns>
 /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
 /// </returns>
 /// <remarks>
 /// In the event that multiple associations exist for the given
 /// <paramref name="distinguishingFactor"/>, it is important for the
 /// implementation for this method to use the <paramref name="securityRequirements"/>
 /// to pick the best (highest grade or longest living as the host's policy may dictate)
 /// association that fits the security requirements.
 /// Associations that are returned that do not meet the security requirements will be
 /// ignored and a new association created.
 /// </remarks>
 public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, SecuritySettings securityRequirements)
 {
     return this.associationStore.GetAssociation(distinguishingFactor, securityRequirements);
 }
Example #58
0
		/// <summary>
		/// Initializes the binding elements for the OAuth channel.
		/// </summary>
		/// <param name="signingBindingElement">The signing binding element.</param>
		/// <param name="store">The nonce store.</param>
		/// <param name="tokenManager">The token manager.</param>
		/// <param name="securitySettings">The security settings.</param>
		/// <returns>
		/// An array of binding elements used to initialize the channel.
		/// </returns>
		private static IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
			Contract.Requires(securitySettings != null);

			var bindingElements = new List<IChannelBindingElement> {
				new OAuthHttpMethodBindingElement(),
				signingBindingElement,
				new StandardExpirationBindingElement(),
				new StandardReplayProtectionBindingElement(store),
			};

			var spTokenManager = tokenManager as IServiceProviderTokenManager;
			var serviceProviderSecuritySettings = securitySettings as ServiceProviderSecuritySettings;
			if (spTokenManager != null && serviceProviderSecuritySettings != null) {
				bindingElements.Insert(0, new TokenHandlingBindingElement(spTokenManager, serviceProviderSecuritySettings));
			}

			return bindingElements.ToArray();
		}
Example #59
0
 public TokenManager(SecuritySettings securitySettings)
 {
     this._SecuritySettings = securitySettings ?? throw new ArgumentNullException(nameof(securitySettings));
 }
Example #60
0
        public void TestInitialize()
        {
            _securitySettings = new SecuritySettings
            {
                EncryptionKey = "273ece6f97dd844d97dd8f4d"
            };
            _rewardPointsSettings = new RewardPointsSettings
            {
                Enabled = false,
            };

            _encryptionService = new EncryptionService(_securitySettings);

            var customer1 = new Customer
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Hashed,
                Active         = true
            };

            string saltKey  = _encryptionService.CreateSaltKey(5);
            string password = _encryptionService.CreatePasswordHash("password", saltKey);

            customer1.PasswordSalt = saltKey;
            customer1.Password     = password;
            AddCustomerToRegisteredRole(customer1);

            var customer2 = new Customer
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer2);

            var customer3 = new Customer
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Encrypted,
                Password       = _encryptionService.EncryptText("password"),
                Active         = true
            };

            AddCustomerToRegisteredRole(customer3);

            var customer4 = new Customer
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            AddCustomerToRegisteredRole(customer4);

            var customer5 = new Customer
            {
                Username       = "******",
                Email          = "*****@*****.**",
                PasswordFormat = PasswordFormat.Clear,
                Password       = "******",
                Active         = true
            };

            //trying to recreate

            var eventPublisher = new Mock <IEventPublisher>();

            eventPublisher.Setup(x => x.Publish(new object()));
            _eventPublisher = eventPublisher.Object;

            _storeService = new Mock <IStoreService>().Object;

            _customerRepo = new Grand.Services.Tests.MongoDBRepositoryTest <Customer>();
            _customerRepo.Insert(customer1);
            _customerRepo.Insert(customer2);
            _customerRepo.Insert(customer3);
            _customerRepo.Insert(customer4);
            _customerRepo.Insert(customer5);

            _customerRoleRepo         = new Mock <IRepository <CustomerRole> >().Object;
            _orderRepo                = new Mock <IRepository <Order> >().Object;
            _forumPostRepo            = new Mock <IRepository <ForumPost> >().Object;
            _forumTopicRepo           = new Mock <IRepository <ForumTopic> >().Object;
            _customerProductPriceRepo = new Mock <IRepository <CustomerProductPrice> >().Object;
            _customerProductRepo      = new Mock <IRepository <CustomerProduct> >().Object;
            _customerHistoryRepo      = new Mock <IRepository <CustomerHistoryPassword> >().Object;
            _customerNoteRepo         = new Mock <IRepository <CustomerNote> >().Object;

            _genericAttributeService       = new Mock <IGenericAttributeService>().Object;
            _newsLetterSubscriptionService = new Mock <INewsLetterSubscriptionService>().Object;
            _localizationService           = new Mock <ILocalizationService>().Object;
            _rewardPointsService           = new Mock <IRewardPointsService>().Object;
            _customerRoleProductRepo       = new Mock <IRepository <CustomerRoleProduct> >().Object;
            _serviceProvider  = new Mock <IServiceProvider>().Object;
            _customerSettings = new CustomerSettings();
            _commonSettings   = new CommonSettings();
            _customerService  = new CustomerService(new TestMemoryCacheManager(new Mock <IMemoryCache>().Object), _customerRepo, _customerRoleRepo, _customerProductRepo, _customerProductPriceRepo,
                                                    _customerHistoryRepo, _customerRoleProductRepo, _customerNoteRepo, _orderRepo, _forumPostRepo, _forumTopicRepo, null, null, _genericAttributeService, null,
                                                    _eventPublisher, _serviceProvider, _customerSettings, _commonSettings);

            _customerRegistrationService = new CustomerRegistrationService(
                _customerService,
                _encryptionService,
                _newsLetterSubscriptionService,
                _localizationService,
                _storeService,
                _eventPublisher,
                _rewardPointsSettings,
                _customerSettings,
                _rewardPointsService);
        }