/// <summary> /// Erstellt eine neue Instanz von TcpCustomServerProtocolSetup. /// </summary> /// <param name="tcpPort">TCP-Anschlußnummer</param> /// <param name="authProvider">Authentifizierungsanbieter</param> public TcpCustomServerProtocolSetup(int tcpPort,IAuthenticationProvider authProvider) : this() { // Werte übernehmen TcpPort = tcpPort; AuthenticationProvider=authProvider; }
public VartotojaiController(IAuthenticationProvider authenticationProvider, ISessionFactory sessionFactory, [LoggedIn] UserInformation loggedInUser, HashAlgorithm hashAlgorithm) { _authenticationProvider = authenticationProvider; _sessionFactory = sessionFactory; _loggedInUser = loggedInUser; _hashAlgorithm = hashAlgorithm; }
public AddGuidColumn(BonoboGitServerContext context) { AuthProvider = DependencyResolver.Current.GetService<IAuthenticationProvider>(); _db = context.Database; if (UpgradeHasAlreadyBeenRun()) { return; } using (var trans = context.Database.BeginTransaction()) { try { RenameTables(); CreateTables(); CopyData(); AddRelations(); DropRenamedTables(); trans.Commit(); } catch (Exception) { trans.Rollback(); throw; } } }
public EventStoreEmbeddedNodeConnection(ConnectionSettings settings, string connectionName, IPublisher publisher, ISubscriber bus, IAuthenticationProvider authenticationProvider) { Ensure.NotNull(publisher, "publisher"); Ensure.NotNull(settings, "settings"); Guid connectionId = Guid.NewGuid(); _settings = settings; _connectionName = connectionName; _publisher = publisher; _authenticationProvider = authenticationProvider; _subscriptionBus = new InMemoryBus("Embedded Client Subscriptions"); _subscriptions = new EmbeddedSubscriber(_subscriptionBus, _authenticationProvider, _settings.Log, connectionId); _subscriptionBus.Subscribe<ClientMessage.SubscriptionConfirmation>(_subscriptions); _subscriptionBus.Subscribe<ClientMessage.SubscriptionDropped>(_subscriptions); _subscriptionBus.Subscribe<ClientMessage.StreamEventAppeared>(_subscriptions); _subscriptionBus.Subscribe<ClientMessage.PersistentSubscriptionConfirmation>(_subscriptions); _subscriptionBus.Subscribe<ClientMessage.PersistentSubscriptionStreamEventAppeared>(_subscriptions); _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.SubscribeToStream>(_publisher.Publish)); _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.UnsubscribeFromStream>(_publisher.Publish)); _subscriptionBus.Subscribe(new AdHocHandler<ClientMessage.ConnectToPersistentSubscription>(_publisher.Publish)); bus.Subscribe(new AdHocHandler<SystemMessage.BecomeShutdown>(_ => Disconnected(this, new ClientConnectionEventArgs(this, new IPEndPoint(IPAddress.None, 0))))); }
public SecureAgentProfile(Guid id, VersionCode version, IPEndPoint agent, string agentName, string authenticationPassphrase, string privacyPassphrase, int authenticationMethod, int privacyMethod, string userName, int timeout) : base(id, version, agent, agentName, userName, timeout) { AuthenticationPassphrase = authenticationPassphrase; PrivacyPassphrase = privacyPassphrase; AuthenticationMethod = authenticationMethod; PrivacyMethod = privacyMethod; switch (AuthenticationMethod) { case 0: _auth = DefaultAuthenticationProvider.Instance; break; case 1: _auth = new MD5AuthenticationProvider(new OctetString(AuthenticationPassphrase)); break; case 2: _auth = new SHA1AuthenticationProvider(new OctetString(AuthenticationPassphrase)); break; } switch (PrivacyMethod) { case 0: _privacy = new DefaultPrivacyProvider(_auth); break; case 1: _privacy = new DESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth); break; case 2: _privacy = new AESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth); break; } }
public SettingsController(IUserReaderService userReaderService, IUserWriterService userWriterService, IAuthenticationProvider authenticationProvider, ILoggerFactory loggerFactory) { _userReaderService = userReaderService; _userWriterService = userWriterService; _authenticationProvider = authenticationProvider; _logger = loggerFactory.GetLogger("Settings"); }
public ServiceUrlBuilder(ServiceType serviceType, IAuthenticationProvider authenticationProvider, string region, bool useInternalUrl) { _serviceType = serviceType; _authenticationProvider = authenticationProvider; _region = region; _useInternalUrl = useInternalUrl; }
public MqttIotHubAdapter(Settings settings, DeviceClientFactoryFunc deviceClientFactory, ISessionStatePersistenceProvider sessionStateManager, IAuthenticationProvider authProvider, ITopicNameRouter topicNameRouter, IQos2StatePersistenceProvider qos2StateProvider) { Contract.Requires(settings != null); Contract.Requires(sessionStateManager != null); Contract.Requires(authProvider != null); Contract.Requires(topicNameRouter != null); if (qos2StateProvider != null) { this.maxSupportedQosToClient = QualityOfService.ExactlyOnce; this.qos2StateProvider = qos2StateProvider; } else { this.maxSupportedQosToClient = QualityOfService.AtLeastOnce; } this.settings = settings; this.deviceClientFactory = deviceClientFactory; this.sessionStateManager = sessionStateManager; this.authProvider = authProvider; this.topicNameRouter = topicNameRouter; this.publishProcessor = new PacketAsyncProcessor<PublishPacket>(this.PublishToServerAsync); this.publishProcessor.Completion.OnFault(ShutdownOnPublishToServerFaultAction); TimeSpan? ackTimeout = this.settings.DeviceReceiveAckCanTimeout ? this.settings.DeviceReceiveAckTimeout : (TimeSpan?)null; this.publishPubAckProcessor = new RequestAckPairProcessor<AckPendingMessageState, PublishPacket>(this.AcknowledgePublishAsync, this.RetransmitNextPublish, ackTimeout); this.publishPubAckProcessor.Completion.OnFault(ShutdownOnPubAckFaultAction); this.publishPubRecProcessor = new RequestAckPairProcessor<AckPendingMessageState, PublishPacket>(this.AcknowledgePublishReceiveAsync, this.RetransmitNextPublish, ackTimeout); this.publishPubRecProcessor.Completion.OnFault(ShutdownOnPubRecFaultAction); this.pubRelPubCompProcessor = new RequestAckPairProcessor<CompletionPendingMessageState, PubRelPacket>(this.AcknowledgePublishCompleteAsync, this.RetransmitNextPublishRelease, ackTimeout); this.pubRelPubCompProcessor.Completion.OnFault(ShutdownOnPubCompFaultAction); }
public LifeCycleManager(IAuthenticationProvider authenticationProvider, String entityType) { Debug.WriteLine("Create new instance of LifeCycleManager for entityType '{0}'", entityType); _entityType = entityType; lock (_lock) { if (null == _staticStateMachineConfigLoader) { LoadAndComposeParts(); _staticStateMachineConfigLoader = _stateMachineConfigLoader; _staticCalloutExecutor = _calloutExecutor; } else { _stateMachineConfigLoader = _staticStateMachineConfigLoader; _calloutExecutor = _staticCalloutExecutor; } } _coreService = new CumulusCoreService.Core(new Uri(ConfigurationManager.AppSettings[CORE_ENDPOINT_URL_KEY])); _coreService.BuildingRequest += CoreServiceOnBuildingRequest; _entityController = new EntityController(authenticationProvider); _stateMachine = new StateMachine.StateMachine(); ConfigureStateMachine(entityType); }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Queueing.ConnectionScheduler"/> class. /// </summary> /// <param name="repoInfo">Repo info.</param> /// <param name="queue">Event queue.</param> /// <param name="sessionFactory">Session factory.</param> /// <param name="authProvider">Auth provider.</param> /// <param name="interval">Retry interval in msec.</param> public ConnectionScheduler( RepoInfo repoInfo, ISyncEventQueue queue, ISessionFactory sessionFactory, IAuthenticationProvider authProvider, int interval = 5000) { if (interval <= 0) { throw new ArgumentException(string.Format("Given Interval \"{0}\" is smaller or equal to null", interval)); } if (repoInfo == null) { throw new ArgumentNullException("repoInfo"); } if (queue == null) { throw new ArgumentNullException("queue"); } if (sessionFactory == null) { throw new ArgumentNullException("sessionFactory"); } if (authProvider == null) { throw new ArgumentNullException("authProvider"); } this.Queue = queue; this.SessionFactory = sessionFactory; this.RepoInfo = repoInfo; this.AuthProvider = authProvider; this.Interval = interval; }
protected override void EstablishContext() { wimpProvider = mocks.StrictMock<IWimpProvider>(); staffInformationProvider = mocks.Stub<IStaffInformationProvider>(); authenticationProvider = mocks.Stub<IAuthenticationProvider>(); userClaimsProvider = mocks.Stub<IUserClaimsProvider>(); }
/// <summary> /// Erstellt eine neue Instanz von HttpCustomServerProtocolSetup. /// </summary> /// <param name="httpPort">HTTP-Anschlußnummer</param> /// <param name="authProvider">Authentifizierungsanbieter</param> public HttpCustomServerProtocolSetup(int httpPort, IAuthenticationProvider authProvider) : this() { // Werte übernehmen HttpPort = httpPort; AuthenticationProvider = authProvider; }
public AccountController(IOpenIdMembershipService openIdMembershipService, IAuthenticationProvider authenticationProvider, IUserService userService, IUserProvider userProvider) { this.openIdMembershipService = openIdMembershipService; this.authenticationProvider = authenticationProvider; this.userService = userService; this.userProvider = userProvider; }
/// <summary> /// Instantiates a new OneDriveClient. /// </summary> /// <param name="baseUrl">The base service URL. For example, "https://api.onedrive.com/v1.0."</param> /// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating request messages.</param> /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending requests.</param> public OneDriveClient( string baseUrl, IAuthenticationProvider authenticationProvider, IHttpProvider httpProvider = null) : base(baseUrl, authenticationProvider, httpProvider) { }
public AuthenticationRegistry(IAuthenticationProvider facebookProvider, IAuthenticationProvider googleProvider, IAuthenticationProvider twitterProvider) { var authenticationService = new AuthenticationService(); if (facebookProvider != null) { authenticationService.AddProvider(facebookProvider); } if (googleProvider != null) { authenticationService.AddProvider(googleProvider); } if (twitterProvider != null) { authenticationService.AddProvider(twitterProvider); } For<IAuthenticationService>() .Use(authenticationService) .Named("Authentication Service."); }
public IdentityClaimsGetOutputClaimsIdentityProvider(IStaffInformationProvider staffInformationProvider, IAuthenticationProvider authenticationProvider, IDashboardUserClaimsInformationProvider<EdFiUserSecurityDetails> dashboardUserClaimsInformationProvider, IHttpRequestProvider httpRequestProvider) { this.staffInformationProvider = staffInformationProvider; this.authenticationProvider = authenticationProvider; this.dashboardUserClaimsInformationProvider = dashboardUserClaimsInformationProvider; this.httpRequestProvider = httpRequestProvider; }
public GetImpersonatedClaimsDataProvider(IWimpProvider wimpProvider, IStaffInformationProvider staffInformationProvider, IAuthenticationProvider authenticationProvider, IUserClaimsProvider userClaimsProvider) { this.wimpProvider = wimpProvider; this.staffInformationProvider = staffInformationProvider; this.authenticationProvider = authenticationProvider; this.userClaimsProvider = userClaimsProvider; }
public AccountProvider(IAuthenticationProvider authenticationProvider, ICaptchaProvider captchaProvider, IEmailProvider emailProvider, IMobileProvider mobileProvider) { _authenticationProvider = authenticationProvider; _captchaProvider = captchaProvider; _emailProvider = emailProvider; _mobileProvider = mobileProvider; }
public void Initialize(IPipeline pipelineRunner) { _authentication = _resolver.Resolve<IAuthenticationProvider>(); pipelineRunner.Notify(ReadCredentials) .After<KnownStages.IBegin>() .And .Before<KnownStages.IHandlerSelection>(); }
public static FlurlClient Authenticate(this FlurlClient client, IAuthenticationProvider authenticationProvider) { var authenticatedMessageHandler = client.HttpMessageHandler as AuthenticatedMessageHandler; if (authenticatedMessageHandler != null) { authenticatedMessageHandler.AuthenticationProvider = authenticationProvider; } return client; }
public void SetUp() { ServiceLocatorInitializer.Init(); controller = new MembershipController(); mockedMembershipProvider = MockRepository.GenerateMock<IMembershipProvider>(); mockedAuthenticationProvider = MockRepository.GenerateMock<IAuthenticationProvider>(); mockedAuthorizationProvider = MockRepository.GenerateMock<IAuthorizationProvider>(); }
public DashboardClaimsGetOutputClaimsIdentityProvider(IStaffInformationProvider staffInformationProvider, IAuthenticationProvider authenticationProvider, IUserClaimsProvider userClaimsProvider, IClaimsIssuedTrackingEventProvider claimsIssuedTrackingEventProvider, IGetImpersonatedClaimsDataProvider getImpersonatedClaimsDataProvider) { this.staffInformationProvider = staffInformationProvider; this.authenticationProvider = authenticationProvider; this.userClaimsProvider = userClaimsProvider; this.ClaimsIssuedTrackingEventProvider = claimsIssuedTrackingEventProvider; this.getImpersonatedClaimsDataProvider = getImpersonatedClaimsDataProvider; }
/// <summary> /// Erzeugt eine neue Instanz von TcpCustomServerProtocolSetup. /// </summary> /// <param name="tcpPort">TCP-Anschlußnummer</param> /// <param name="authProvider">Authentifizierungsanbieter</param> /// <param name="encryption">Gibt an, ob die Kommunikation verschlüssel werden soll</param> /// <param name="algorithm">Verschlüsselungsalgorithmus (z.B. "3DES")</param> public TcpCustomServerProtocolSetup(int tcpPort,IAuthenticationProvider authProvider,bool encryption, string algorithm) : this() { // Werte übernehmen TcpPort=tcpPort; AuthenticationProvider=authProvider; _encryption = encryption; _algorithm = algorithm; }
/// <summary> /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class. /// </summary> public MainWindowViewModel(IUIVisualizerService uiVisualizerService, IAuthenticationProvider authenticationProvider) { _uiVisualizerService = uiVisualizerService; _authenticationProvider = authenticationProvider; RoleCollection = new ObservableCollection<string>(new [] { "Read-only", "Administrator" }); ShowView = new Command(OnShowViewExecute, OnShowViewCanExecute); }
public PeopleController(IPersonManagementService personManagementService, IPersonSearchManagementService personSearchManagementService, IAuthenticationProvider authenticationProvider) { Check.Require(personManagementService != null, "personManagementService may not be null"); _personManagementService = personManagementService; _personSearchManagementService = personSearchManagementService; _authenticationProvider = authenticationProvider; }
public FakeNancyBootstrapper(IBrightstarService brightstarService, IAuthenticationProvider authenticationProvider, AbstractStorePermissionsProvider storePermissionsProvider, AbstractSystemPermissionsProvider systemPermissionsProvider) { _brightstarService = brightstarService; _authenticationProvider = authenticationProvider; _systemPermissionsProvider = systemPermissionsProvider; _storePermissionsProvider = storePermissionsProvider; }
public AccountController(IAuthenticationProvider<CustomPrincipal> authenticationProvider, Context context, ISaltGenerator saltGenerator, IPasswordSalter passwordSalter) { _authenticationProvider = authenticationProvider; this._context = context; _saltGenerator = saltGenerator; _passwordSalter = passwordSalter; }
/// <summary> /// Initializes a new instance of the <see cref="ContentDeliveryNetworkService"/> class. /// </summary> /// <param name="authenticationProvider">The authentication provider.</param> /// <param name="region">The cloud region.</param> /// <param name="useInternalUrl">if set to <c>true</c> uses the internal URLs specified in the ServiceCatalog, otherwise the public URLs are used.</param> /// <exception cref="ArgumentNullException">If the <paramref name="authenticationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">If the <paramref name="region"/> is <see langword="null"/> or empty.</exception> public ContentDeliveryNetworkService(IAuthenticationProvider authenticationProvider, string region, bool useInternalUrl = false) { if (authenticationProvider == null) throw new ArgumentNullException("authenticationProvider"); if (string.IsNullOrEmpty(region)) throw new ArgumentException("region cannot be null or empty", "region"); _authenticationProvider = authenticationProvider; _urlBuilder = new ServiceUrlBuilder(ServiceType.ContentDeliveryNetwork, authenticationProvider, region, useInternalUrl); }
//================================================================================================================= /// <summary> /// Ctor for view model /// </summary> //================================================================================================================= public SignInPageViewModel(INavigationService navigationService, IAuthenticationProvider authProvider, IUnityContainer container, IRestClient client, ConfigurationSettings settings) { this.NavigationService = navigationService; this.AuthenticationProvider = authProvider; this.NavigateCommand = new DelegateCommand(GoBack); this.PickOAuthProviderCommand = new DelegateCommand(OnPickOAuthProvider); this.SignInCommand = new DelegateCommand(OnSignInClicked); this.Settings = settings; this.Container = container; this.Client = client; }
protected override void EstablishContext() { base.EstablishContext(); staffInformationFromEmailProvider = mocks.StrictMock<IStaffInformationFromEmailProvider>(); authenticationProvider = mocks.StrictMock<IAuthenticationProvider>(); httpContextItemsProvider = mocks.StrictMock<IHttpContextItemsProvider>(); userClaimsProvider = mocks.StrictMock<IUserClaimsProvider>(); ClaimsIssuedTrackingEventProvider = mocks.StrictMock<IClaimsIssuedTrackingEventProvider>(); getImpersonatedClaimsDataProvider = mocks.StrictMock<IGetImpersonatedClaimsDataProvider>(); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceEndpoint"/> class. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="authenticationProvider">The authentication provider.</param> /// <param name="region">The region.</param> /// <param name="useInternalUrl">Specifies if internal URLs should be used.</param> public ServiceEndpoint(IServiceType serviceType, IAuthenticationProvider authenticationProvider, string region, bool useInternalUrl) : this(serviceType, authenticationProvider, region, useInternalUrl, microversion : null, microversionHeader : null) { }
/// <summary> /// Get an instance of EducationServiceClient /// </summary> public static EducationServiceClient GetEducationServiceClient(IAuthenticationProvider authenticationProvider) { var serviceRoot = new Uri(new Uri(Constants.Resources.MSGraph), Constants.Resources.MSGraphVersion); return(new EducationServiceClient(serviceRoot, authenticationProvider)); }
public ServiceClient(IAuthenticationProvider authenticationProvider, Uri baseUrl) { _authenticationProvider = authenticationProvider; _baseUrl = baseUrl; }
public AdalServiceInfoProvider(IAuthenticationProvider authenticationProvider, IWebAuthenticationUi webAuthenticationUi) : base(authenticationProvider, webAuthenticationUi) { }
protected DiscoveryServiceHelperBase(IAuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; }
/// <summary> /// Construct a new <see cref="AuthenticationHandler"/> /// <param name="authenticationProvider">An authentication provider to pass to <see cref="AuthenticationHandler"/> for authenticating requests.</param> /// </summary> /// <param name="authOption">An OPTIONAL <see cref="Microsoft.Graph.AuthenticationHandlerOption"/> to configure <see cref="AuthenticationHandler"/></param> public AuthenticationHandler(IAuthenticationProvider authenticationProvider, AuthenticationHandlerOption authOption = null) { AuthenticationProvider = authenticationProvider; AuthOption = authOption ?? new AuthenticationHandlerOption(); }
public Handler (ITransactionScheduleRepository transactionRepository, IMapper mapper, IAuthenticationProvider authenticationProvider) : base(null, transactionRepository, mapper, authenticationProvider) { }
public KubeBaseRequest(IAuthenticationProvider authProvider, KubeOptions settings) { _auth = authProvider; _settings = settings; }
public static void Main(string[] args) { string community = "public"; bool showHelp = false; bool showVersion = false; VersionCode version = VersionCode.V2; // GET BULK is available in SNMP v2 and above. int timeout = 1000; int retry = 0; Levels level = Levels.Reportable; string user = string.Empty; string authentication = string.Empty; string authPhrase = string.Empty; string privacy = string.Empty; string privPhrase = string.Empty; int maxRepetitions = 10; int nonRepeaters = 0; OptionSet p = new OptionSet() .Add("c:", "-c for community name, (default is public)", delegate(string v) { if (v != null) { community = v; } }) .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate(string v) { if (v.ToUpperInvariant() == "NOAUTHNOPRIV") { level = Levels.Reportable; } else if (v.ToUpperInvariant() == "AUTHNOPRIV") { level = Levels.Authentication | Levels.Reportable; } else if (v.ToUpperInvariant() == "AUTHPRIV") { level = Levels.Authentication | Levels.Privacy | Levels.Reportable; } else { throw new ArgumentException("no such security mode: " + v); } }) .Add("Cn:", "-Cn for non-repeaters (default is 0)", delegate(string v) { nonRepeaters = int.Parse(v); }) .Add("Cr:", "-Cr for max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); }) .Add("a:", "-a for authentication method (MD5 or SHA)", delegate(string v) { authentication = v; }) .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; }) .Add("x:", "-x for privacy method", delegate(string v) { privacy = v; }) .Add("X:", "-X for privacy passphrase", delegate(string v) { privPhrase = v; }) .Add("u:", "-u for security name", delegate(string v) { user = v; }) .Add("h|?|help", "-h, -?, -help for help.", delegate(string v) { showHelp = v != null; }) .Add("V", "-V to display version number of this application.", delegate(string v) { showVersion = v != null; }) .Add("t:", "-t for timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; }) .Add("r:", "-r for retry count (default is 0)", delegate(string v) { retry = int.Parse(v); }) .Add("v:", "-v for SNMP version (2 and 3 are currently supported)", delegate(string v) { switch (int.Parse(v)) { case 2: version = VersionCode.V2; break; case 3: version = VersionCode.V3; break; default: throw new ArgumentException("no such version: " + v); } }); List <string> extra = p.Parse(args); if (showHelp) { ShowHelp(); return; } if (showVersion) { Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); return; } if (extra.Count < 2) { ShowHelp(); return; } IPAddress ip; bool parsed = IPAddress.TryParse(extra[0], out ip); if (!parsed) { foreach (IPAddress address in Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork)) { ip = address; break; } if (ip == null) { Console.WriteLine("invalid host or wrong IP address found: " + extra[0]); return; } } try { List <Variable> vList = new List <Variable>(); for (int i = 1; i < extra.Count; i++) { Variable test = new Variable(new ObjectIdentifier(extra[i])); vList.Add(test); } IPEndPoint receiver = new IPEndPoint(ip, 161); if (version != VersionCode.V3) { GetBulkRequestMessage message = new GetBulkRequestMessage(0, version, new OctetString(community), nonRepeaters, maxRepetitions, vList); ISnmpMessage response = message.GetResponse(timeout, receiver); if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError { throw ErrorException.Create( "error in response", receiver.Address, response); } foreach (Variable variable in response.Pdu().Variables) { Console.WriteLine(variable); } return; } if (string.IsNullOrEmpty(user)) { Console.WriteLine("User name need to be specified for v3."); return; } IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication ? GetAuthenticationProviderByName(authentication, authPhrase) : DefaultAuthenticationProvider.Instance; IPrivacyProvider priv; if ((level & Levels.Privacy) == Levels.Privacy) { priv = new DESPrivacyProvider(new OctetString(privPhrase), auth); } else { priv = new DefaultPrivacyProvider(auth); } Discovery discovery = Messenger.NextDiscovery; ReportMessage report = discovery.GetResponse(timeout, receiver); GetBulkRequestMessage request = new GetBulkRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), nonRepeaters, maxRepetitions, vList, priv, Messenger.MaxMessageSize, report); ISnmpMessage reply = request.GetResponse(timeout, receiver); if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError { throw ErrorException.Create( "error in response", receiver.Address, reply); } foreach (Variable v in reply.Pdu().Variables) { Console.WriteLine(v); } } catch (SnmpException ex) { Console.WriteLine(ex); } catch (SocketException ex) { Console.WriteLine(ex); } }
/// <summary> /// Creates the list of scripts that should be executed on app start. Ordering matters! /// </summary> public static IEnumerable <IUpdateScript> GetScriptsBySqlProviderName(string sqlProvider, IAuthenticationProvider authenticationProvider) { switch (sqlProvider) { case "Microsoft.EntityFrameworkCore.Sqlite": return(new List <IUpdateScript> { new Sqlite.InitialCreateScript(), new UsernamesToLower(), new Sqlite.AddAuditPushUser(), new Sqlite.AddGroup(), new Sqlite.AddRepositoryLogo(), new Sqlite.AddGuidColumn(authenticationProvider), new Sqlite.AddRepoPushColumn(), new Sqlite.AddRepoLinksColumn(), new Sqlite.InsertDefaultData() }); case "Microsoft.EntityFrameworkCore.SqlServer": return(new List <IUpdateScript> { new SqlServer.InitialCreateScript(), new UsernamesToLower(), new SqlServer.AddAuditPushUser(), new SqlServer.AddGroup(), new SqlServer.AddRepositoryLogo(), new SqlServer.AddGuidColumn(authenticationProvider), new SqlServer.AddRepoPushColumn(), new SqlServer.AddRepoLinksColumn(), new SqlServer.InsertDefaultData() }); default: throw new NotImplementedException($"The provider '{sqlProvider}' is not supported yet"); } }
public AuthHandler(IAuthenticationProvider authenticationProvider, HttpMessageHandler innerHandler) { InnerHandler = innerHandler; _authenticationProvider = authenticationProvider; }
public Route NoAuthenticationProvider() { _authenticationProvider = null; return(this); }
/// <summary /> public ComputeService(IAuthenticationProvider authenticationProvider, string region, bool useInternalUrl) { _computeApi = new ComputeApi(ServiceType.Compute, authenticationProvider, region, useInternalUrl); }
public AdalServiceInfoProvider(IAuthenticationProvider authenticationProvider) : this(authenticationProvider, new WebAuthenticationBrokerWebAuthenticationUi()) { }
public EducationServiceClient(Uri serviceRoot, IAuthenticationProvider authenticationProvider) { this.serviceRoot = serviceRoot.ToString().TrimEnd('/'); this.authenticationProvider = authenticationProvider; }
protected override void ProcessRecord() { base.ProcessRecord(); IAuthContext authConfig = new AuthContext { TenantId = TenantId }; if (ParameterSetName == Constants.UserParameterSet) { // 2 mins timeout. 1 min < HTTP timeout. TimeSpan authTimeout = new TimeSpan(0, 0, Constants.MaxDeviceCodeTimeOut); cancellationTokenSource = new CancellationTokenSource(authTimeout); authConfig.AuthType = AuthenticationType.Delegated; authConfig.Scopes = Scopes ?? new string[] { "User.Read" }; // Default to CurrentUser but allow the customer to change this via `ContextScope` param. authConfig.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.CurrentUser; } else { cancellationTokenSource = new CancellationTokenSource(); authConfig.AuthType = AuthenticationType.AppOnly; authConfig.ClientId = ClientId; authConfig.CertificateThumbprint = CertificateThumbprint; authConfig.CertificateName = CertificateName; // Default to Process but allow the customer to change this via `ContextScope` param. authConfig.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.Process; } CancellationToken cancellationToken = cancellationTokenSource.Token; try { // Gets a static instance of IAuthenticationProvider when the client app hasn't changed. IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(authConfig); IClientApplicationBase clientApplication = null; if (ParameterSetName == Constants.UserParameterSet) { clientApplication = (authProvider as DeviceCodeProvider).ClientApplication; } else { clientApplication = (authProvider as ClientCredentialProvider).ClientApplication; } // Incremental scope consent without re-instantiating the auth provider. We will use a static instance. GraphRequestContext graphRequestContext = new GraphRequestContext(); graphRequestContext.CancellationToken = cancellationToken; graphRequestContext.MiddlewareOptions = new Dictionary <string, IMiddlewareOption> { { typeof(AuthenticationHandlerOption).ToString(), new AuthenticationHandlerOption { AuthenticationProviderOption = new AuthenticationProviderOption { Scopes = authConfig.Scopes, ForceRefresh = ForceRefresh } } } }; // Trigger consent. HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me"); httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext); authProvider.AuthenticateRequestAsync(httpRequestMessage).GetAwaiter().GetResult(); var accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult(); var account = accounts.FirstOrDefault(); JwtPayload jwtPayload = JwtHelpers.DecodeToObject <JwtPayload>(httpRequestMessage.Headers.Authorization?.Parameter); authConfig.Scopes = jwtPayload?.Scp?.Split(' ') ?? jwtPayload?.Roles; authConfig.TenantId = jwtPayload?.Tid ?? account?.HomeAccountId?.TenantId; authConfig.AppName = jwtPayload?.AppDisplayname; authConfig.Account = jwtPayload?.Upn ?? account?.Username; // Save auth context to session state. GraphSession.Instance.AuthContext = authConfig; } catch (AuthenticationException authEx) { if ((authEx.InnerException is TaskCanceledException) && cancellationToken.IsCancellationRequested) { throw new Exception($"Device code terminal timed-out after {Constants.MaxDeviceCodeTimeOut} seconds. Please try again."); } else { throw authEx.InnerException ?? authEx; } } catch (Exception ex) { throw ex.InnerException ?? ex; } WriteObject("Welcome To Microsoft Graph!"); }
/// <summary> /// Construct a new <see cref="AuthenticationHandler"/> /// </summary> /// <param name="authenticationProvider">An authentication provider to pass to <see cref="AuthenticationHandler"/> for authenticating requests.</param> /// <param name="innerHandler">A HTTP message handler to pass to the <see cref="AuthenticationHandler"/> for sending requests.</param> /// <param name="authOption">An OPTIONAL <see cref="Microsoft.Graph.AuthenticationHandlerOption"/> to configure <see cref="AuthenticationHandler"/></param> public AuthenticationHandler(IAuthenticationProvider authenticationProvider, HttpMessageHandler innerHandler, AuthenticationHandlerOption authOption = null) : this(authenticationProvider, authOption) { InnerHandler = innerHandler; AuthenticationProvider = authenticationProvider; }
/// <summary> /// Instantiates a new GraphServiceClient. /// </summary> /// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating request messages.</param> /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending requests.</param> public GraphServiceClient( IAuthenticationProvider authenticationProvider, IHttpProvider httpProvider = null) : this("https://graph.microsoft.com/v1.0", authenticationProvider, httpProvider) { }
internal RequestSettings(string baseUrl, IAuthenticationProvider authenticationProvider = null, HeaderCollection globalHeaders = null) { BaseUrl = baseUrl; AuthenticationProvider = authenticationProvider; GlobalHeaders = globalHeaders; }
/// <summary> /// Retry sending HTTP request /// </summary> /// <param name="httpResponseMessage">The <see cref="HttpResponseMessage"/>to send.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>to send.</param> /// <param name="authProvider">An authentication provider to pass to <see cref="AuthenticationHandler"/> for authenticating requests.</param> /// <returns></returns> private async Task <HttpResponseMessage> SendRetryAsync(HttpResponseMessage httpResponseMessage, IAuthenticationProvider authProvider, CancellationToken cancellationToken) { int retryAttempt = 0; while (retryAttempt < MaxRetry) { // general clone request with internal CloneAsync (see CloneAsync for details) extension method var newRequest = await httpResponseMessage.RequestMessage.CloneAsync(); // extract the www-authenticate header and add claims to the request context if (httpResponseMessage.Headers.WwwAuthenticate.Any()) { var wwwAuthenticateHeader = httpResponseMessage.Headers.WwwAuthenticate.ToString(); AddClaimsToRequestContext(newRequest, wwwAuthenticateHeader); } // Authenticate request using AuthenticationProvider await authProvider.AuthenticateRequestAsync(newRequest); httpResponseMessage = await base.SendAsync(newRequest, cancellationToken); retryAttempt++; if (!IsUnauthorized(httpResponseMessage) || !newRequest.IsBuffered()) { // Re-issue the request to get a new access token return(httpResponseMessage); } } return(httpResponseMessage); }
public MyContextFactory(IPnPContextFactory contextFactory, IConfiguration configuration, IAuthenticationProvider msalAuthProvider) { _configuration = configuration; _contextFactory = contextFactory; _msalAuthProvider = msalAuthProvider; }
public async Task <User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession) { if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException(nameof(username)); } var user = Users .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase)); var success = false; IAuthenticationProvider authenticationProvider = null; if (user != null) { var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false); authenticationProvider = authResult.Item1; success = authResult.Item2; } else { // user is null var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false); authenticationProvider = authResult.Item1; success = authResult.Item2; if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider)) { user = await CreateUser(username).ConfigureAwait(false); var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy; if (hasNewUserPolicy != null) { var policy = hasNewUserPolicy.GetNewUserPolicy(); UpdateUserPolicy(user, policy, true); } } } if (success && user != null && authenticationProvider != null) { var providerId = GetAuthenticationProviderId(authenticationProvider); if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase)) { user.Policy.AuthenticationProviderId = providerId; UpdateUserPolicy(user, user.Policy, true); } } if (user == null) { throw new SecurityException("Invalid username or password entered."); } if (user.Policy.IsDisabled) { throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name)); } if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint)) { throw new SecurityException("Forbidden."); } if (!user.IsParentalScheduleAllowed()) { throw new SecurityException("User is not allowed access at this time."); } // Update LastActivityDate and LastLoginDate, then save if (success) { if (isUserSession) { user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow; UpdateUser(user); } UpdateInvalidLoginAttemptCount(user, 0); } else { UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1); } _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied"); return(success ? user : null); }
public InfoControllerBuilder WithAuthenticationProvider(IAuthenticationProvider authenticationProvider) { _authenticationProvider = authenticationProvider; return(this); }
private static string GetAuthenticationProviderId(IAuthenticationProvider provider) { return(provider.GetType().FullName); }
public StudentAbsencesLocationQueries(Student360Context db, IAuthenticationProvider auth) { _db = db; _auth = auth; }
public ClusterVNode(TFChunkDb db, ClusterVNodeSettings vNodeSettings, IGossipSeedSource gossipSeedSource, InfoController infoController, params ISubsystem[] subsystems) { Ensure.NotNull(db, "db"); Ensure.NotNull(vNodeSettings, "vNodeSettings"); Ensure.NotNull(gossipSeedSource, "gossipSeedSource"); var isSingleNode = vNodeSettings.ClusterNodeCount == 1; _nodeInfo = vNodeSettings.NodeInfo; _mainBus = new InMemoryBus("MainBus"); var forwardingProxy = new MessageForwardingProxy(); //start watching jitter HistogramService.StartJitterMonitor(); if (vNodeSettings.EnableHistograms) { HistogramService.CreateHistograms(); } // MISC WORKERS _workerBuses = Enumerable.Range(0, vNodeSettings.WorkerThreads).Select(queueNum => new InMemoryBus(string.Format("Worker #{0} Bus", queueNum + 1), watchSlowMsg: true, slowMsgThreshold: TimeSpan.FromMilliseconds(200))).ToArray(); _workersHandler = new MultiQueuedHandler( vNodeSettings.WorkerThreads, queueNum => new QueuedHandlerThreadPool(_workerBuses[queueNum], string.Format("Worker #{0}", queueNum + 1), groupName: "Workers", watchSlowMsg: true, slowMsgThreshold: TimeSpan.FromMilliseconds(200))); _controller = new ClusterVNodeController((IPublisher)_mainBus, _nodeInfo, db, vNodeSettings, this, forwardingProxy); _mainQueue = new QueuedHandler(_controller, "MainQueue"); _controller.SetMainQueue(_mainQueue); _subsystems = subsystems; //SELF _mainBus.Subscribe <SystemMessage.StateChangeMessage>(this); _mainBus.Subscribe <SystemMessage.BecomeShutdown>(this); _mainBus.Subscribe <UserManagementMessage.UserManagementServiceInitialized>(this); // MONITORING var monitoringInnerBus = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false); var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false); var monitoringQueue = new QueuedHandlerThreadPool(monitoringInnerBus, "MonitoringQueue", true, TimeSpan.FromMilliseconds(100)); var monitoring = new MonitoringService(monitoringQueue, monitoringRequestBus, _mainQueue, db.Config.WriterCheckpoint, db.Config.Path, vNodeSettings.StatsPeriod, _nodeInfo.ExternalHttp, vNodeSettings.StatsStorage, _nodeInfo.ExternalTcp); _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.SystemInit, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.StateChangeMessage, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.BecomeShuttingDown, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.BecomeShutdown, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom <ClientMessage.WriteEventsCompleted, Message>()); monitoringInnerBus.Subscribe <SystemMessage.SystemInit>(monitoring); monitoringInnerBus.Subscribe <SystemMessage.StateChangeMessage>(monitoring); monitoringInnerBus.Subscribe <SystemMessage.BecomeShuttingDown>(monitoring); monitoringInnerBus.Subscribe <SystemMessage.BecomeShutdown>(monitoring); monitoringInnerBus.Subscribe <ClientMessage.WriteEventsCompleted>(monitoring); monitoringInnerBus.Subscribe <MonitoringMessage.GetFreshStats>(monitoring); monitoringInnerBus.Subscribe <MonitoringMessage.GetFreshTcpConnectionStats>(monitoring); var truncPos = db.Config.TruncateCheckpoint.Read(); if (truncPos != -1) { Log.Info("Truncate checkpoint is present. Truncate: {0} (0x{0:X}), Writer: {1} (0x{1:X}), Chaser: {2} (0x{2:X}), Epoch: {3} (0x{3:X})", truncPos, db.Config.WriterCheckpoint.Read(), db.Config.ChaserCheckpoint.Read(), db.Config.EpochCheckpoint.Read()); var truncator = new TFChunkDbTruncator(db.Config); truncator.TruncateDb(truncPos); } // STORAGE SUBSYSTEM db.Open(vNodeSettings.VerifyDbHash); var indexPath = vNodeSettings.Index ?? Path.Combine(db.Config.Path, "index"); var readerPool = new ObjectPool <ITransactionFileReader>( "ReadIndex readers pool", ESConsts.PTableInitialReaderCount, ESConsts.PTableMaxReaderCount, () => new TFChunkReader(db, db.Config.WriterCheckpoint)); var tableIndex = new TableIndex(indexPath, () => new HashListMemTable(maxSize: vNodeSettings.MaxMemtableEntryCount * 2), () => new TFReaderLease(readerPool), maxSizeForMemory: vNodeSettings.MaxMemtableEntryCount, maxTablesPerLevel: 2, inMem: db.Config.InMemDb, indexCacheDepth: vNodeSettings.IndexCacheDepth); var hash = new XXHashUnsafe(); var readIndex = new ReadIndex(_mainQueue, readerPool, tableIndex, hash, ESConsts.StreamInfoCacheCapacity, Application.IsDefined(Application.AdditionalCommitChecks), Application.IsDefined(Application.InfiniteMetastreams) ? int.MaxValue : 1); var writer = new TFChunkWriter(db); var epochManager = new EpochManager(ESConsts.CachedEpochCount, db.Config.EpochCheckpoint, writer, initialReaderCount: 1, maxReaderCount: 5, readerFactory: () => new TFChunkReader(db, db.Config.WriterCheckpoint)); epochManager.Init(); var storageWriter = new ClusterStorageWriterService(_mainQueue, _mainBus, vNodeSettings.MinFlushDelay, db, writer, readIndex.IndexWriter, epochManager, () => readIndex.LastCommitPosition); // subscribes internally monitoringRequestBus.Subscribe <MonitoringMessage.InternalStatsRequest>(storageWriter); var storageReader = new StorageReaderService(_mainQueue, _mainBus, readIndex, ESConsts.StorageReaderThreadCount, db.Config.WriterCheckpoint); _mainBus.Subscribe <SystemMessage.SystemInit>(storageReader); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(storageReader); _mainBus.Subscribe <SystemMessage.BecomeShutdown>(storageReader); monitoringRequestBus.Subscribe <MonitoringMessage.InternalStatsRequest>(storageReader); var chaser = new TFChunkChaser(db, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint); var storageChaser = new StorageChaser(_mainQueue, db.Config.WriterCheckpoint, chaser, readIndex.IndexCommitter, epochManager); #if DEBUG QueueStatsCollector.InitializeCheckpoints( _nodeInfo.DebugIndex, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint); #endif _mainBus.Subscribe <SystemMessage.SystemInit>(storageChaser); _mainBus.Subscribe <SystemMessage.SystemStart>(storageChaser); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(storageChaser); // AUTHENTICATION INFRASTRUCTURE - delegate to plugins _internalAuthenticationProvider = vNodeSettings.AuthenticationProviderFactory.BuildAuthenticationProvider(_mainQueue, _mainBus, _workersHandler, _workerBuses); Ensure.NotNull(_internalAuthenticationProvider, "authenticationProvider"); { // EXTERNAL TCP var extTcpService = new TcpService(_mainQueue, _nodeInfo.ExternalTcp, _workersHandler, TcpServiceType.External, TcpSecurityType.Normal, new ClientTcpDispatcher(), vNodeSettings.ExtTcpHeartbeatInterval, vNodeSettings.ExtTcpHeartbeatTimeout, _internalAuthenticationProvider, null); _mainBus.Subscribe <SystemMessage.SystemInit>(extTcpService); _mainBus.Subscribe <SystemMessage.SystemStart>(extTcpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(extTcpService); // EXTERNAL SECURE TCP if (_nodeInfo.ExternalSecureTcp != null) { var extSecTcpService = new TcpService(_mainQueue, _nodeInfo.ExternalSecureTcp, _workersHandler, TcpServiceType.External, TcpSecurityType.Secure, new ClientTcpDispatcher(), vNodeSettings.ExtTcpHeartbeatInterval, vNodeSettings.ExtTcpHeartbeatTimeout, _internalAuthenticationProvider, vNodeSettings.Certificate); _mainBus.Subscribe <SystemMessage.SystemInit>(extSecTcpService); _mainBus.Subscribe <SystemMessage.SystemStart>(extSecTcpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(extSecTcpService); } if (!isSingleNode) { // INTERNAL TCP var intTcpService = new TcpService(_mainQueue, _nodeInfo.InternalTcp, _workersHandler, TcpServiceType.Internal, TcpSecurityType.Normal, new InternalTcpDispatcher(), vNodeSettings.IntTcpHeartbeatInterval, vNodeSettings.IntTcpHeartbeatTimeout, _internalAuthenticationProvider, null); _mainBus.Subscribe <SystemMessage.SystemInit>(intTcpService); _mainBus.Subscribe <SystemMessage.SystemStart>(intTcpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(intTcpService); // INTERNAL SECURE TCP if (_nodeInfo.InternalSecureTcp != null) { var intSecTcpService = new TcpService(_mainQueue, _nodeInfo.InternalSecureTcp, _workersHandler, TcpServiceType.Internal, TcpSecurityType.Secure, new InternalTcpDispatcher(), vNodeSettings.IntTcpHeartbeatInterval, vNodeSettings.IntTcpHeartbeatTimeout, _internalAuthenticationProvider, vNodeSettings.Certificate); _mainBus.Subscribe <SystemMessage.SystemInit>(intSecTcpService); _mainBus.Subscribe <SystemMessage.SystemStart>(intSecTcpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(intSecTcpService); } } } SubscribeWorkers(bus => { var tcpSendService = new TcpSendService(); // ReSharper disable RedundantTypeArgumentsOfMethod bus.Subscribe <TcpMessage.TcpSend>(tcpSendService); // ReSharper restore RedundantTypeArgumentsOfMethod }); var httpAuthenticationProviders = new List <HttpAuthenticationProvider> { new BasicHttpAuthenticationProvider(_internalAuthenticationProvider), }; if (vNodeSettings.EnableTrustedAuth) { httpAuthenticationProviders.Add(new TrustedHttpAuthenticationProvider()); } httpAuthenticationProviders.Add(new AnonymousHttpAuthenticationProvider()); var httpPipe = new HttpMessagePipe(); var httpSendService = new HttpSendService(httpPipe, forwardRequests: true); _mainBus.Subscribe <SystemMessage.StateChangeMessage>(httpSendService); _mainBus.Subscribe(new WideningHandler <HttpMessage.SendOverHttp, Message>(_workersHandler)); SubscribeWorkers(bus => { bus.Subscribe <HttpMessage.HttpSend>(httpSendService); bus.Subscribe <HttpMessage.HttpSendPart>(httpSendService); bus.Subscribe <HttpMessage.HttpBeginSend>(httpSendService); bus.Subscribe <HttpMessage.HttpEndSend>(httpSendService); bus.Subscribe <HttpMessage.SendOverHttp>(httpSendService); }); _mainBus.Subscribe <SystemMessage.StateChangeMessage>(infoController); var adminController = new AdminController(_mainQueue); var pingController = new PingController(); var histogramController = new HistogramController(); var statController = new StatController(monitoringQueue, _workersHandler); var atomController = new AtomController(httpSendService, _mainQueue, _workersHandler, vNodeSettings.DisableHTTPCaching); var gossipController = new GossipController(_mainQueue, _workersHandler, vNodeSettings.GossipTimeout); var persistentSubscriptionController = new PersistentSubscriptionController(httpSendService, _mainQueue, _workersHandler); var electController = new ElectController(_mainQueue); // HTTP SENDERS gossipController.SubscribeSenders(httpPipe); electController.SubscribeSenders(httpPipe); // EXTERNAL HTTP _externalHttpService = new HttpService(ServiceAccessibility.Public, _mainQueue, new TrieUriRouter(), _workersHandler, vNodeSettings.LogHttpRequests, vNodeSettings.ExtHttpPrefixes); _externalHttpService.SetupController(persistentSubscriptionController); if (vNodeSettings.AdminOnPublic) { _externalHttpService.SetupController(adminController); } _externalHttpService.SetupController(pingController); _externalHttpService.SetupController(infoController); if (vNodeSettings.StatsOnPublic) { _externalHttpService.SetupController(statController); } _externalHttpService.SetupController(atomController); if (vNodeSettings.GossipOnPublic) { _externalHttpService.SetupController(gossipController); } _externalHttpService.SetupController(histogramController); _mainBus.Subscribe <SystemMessage.SystemInit>(_externalHttpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(_externalHttpService); _mainBus.Subscribe <HttpMessage.PurgeTimedOutRequests>(_externalHttpService); // INTERNAL HTTP if (!isSingleNode) { _internalHttpService = new HttpService(ServiceAccessibility.Private, _mainQueue, new TrieUriRouter(), _workersHandler, vNodeSettings.LogHttpRequests, vNodeSettings.IntHttpPrefixes); _internalHttpService.SetupController(adminController); _internalHttpService.SetupController(pingController); _internalHttpService.SetupController(infoController); _internalHttpService.SetupController(statController); _internalHttpService.SetupController(atomController); _internalHttpService.SetupController(gossipController); _internalHttpService.SetupController(electController); _internalHttpService.SetupController(histogramController); _internalHttpService.SetupController(persistentSubscriptionController); } // Authentication plugin HTTP vNodeSettings.AuthenticationProviderFactory.RegisterHttpControllers(_externalHttpService, _internalHttpService, httpSendService, _mainQueue, _workersHandler); if (_internalHttpService != null) { _mainBus.Subscribe <SystemMessage.SystemInit>(_internalHttpService); _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(_internalHttpService); _mainBus.Subscribe <HttpMessage.PurgeTimedOutRequests>(_internalHttpService); } SubscribeWorkers(bus => { HttpService.CreateAndSubscribePipeline(bus, httpAuthenticationProviders.ToArray()); }); // REQUEST FORWARDING var forwardingService = new RequestForwardingService(_mainQueue, forwardingProxy, TimeSpan.FromSeconds(1)); _mainBus.Subscribe <SystemMessage.SystemStart>(forwardingService); _mainBus.Subscribe <SystemMessage.RequestForwardingTimerTick>(forwardingService); _mainBus.Subscribe <ClientMessage.NotHandled>(forwardingService); _mainBus.Subscribe <ClientMessage.WriteEventsCompleted>(forwardingService); _mainBus.Subscribe <ClientMessage.TransactionStartCompleted>(forwardingService); _mainBus.Subscribe <ClientMessage.TransactionWriteCompleted>(forwardingService); _mainBus.Subscribe <ClientMessage.TransactionCommitCompleted>(forwardingService); _mainBus.Subscribe <ClientMessage.DeleteStreamCompleted>(forwardingService); // REQUEST MANAGEMENT var requestManagement = new RequestManagementService(_mainQueue, vNodeSettings.PrepareAckCount, vNodeSettings.CommitAckCount, vNodeSettings.PrepareTimeout, vNodeSettings.CommitTimeout); _mainBus.Subscribe <SystemMessage.SystemInit>(requestManagement); _mainBus.Subscribe <ClientMessage.WriteEvents>(requestManagement); _mainBus.Subscribe <ClientMessage.TransactionStart>(requestManagement); _mainBus.Subscribe <ClientMessage.TransactionWrite>(requestManagement); _mainBus.Subscribe <ClientMessage.TransactionCommit>(requestManagement); _mainBus.Subscribe <ClientMessage.DeleteStream>(requestManagement); _mainBus.Subscribe <StorageMessage.RequestCompleted>(requestManagement); _mainBus.Subscribe <StorageMessage.CheckStreamAccessCompleted>(requestManagement); _mainBus.Subscribe <StorageMessage.AlreadyCommitted>(requestManagement); _mainBus.Subscribe <StorageMessage.CommitAck>(requestManagement); _mainBus.Subscribe <StorageMessage.PrepareAck>(requestManagement); _mainBus.Subscribe <StorageMessage.WrongExpectedVersion>(requestManagement); _mainBus.Subscribe <StorageMessage.InvalidTransaction>(requestManagement); _mainBus.Subscribe <StorageMessage.StreamDeleted>(requestManagement); _mainBus.Subscribe <StorageMessage.RequestManagerTimerTick>(requestManagement); // SUBSCRIPTIONS var subscrBus = new InMemoryBus("SubscriptionsBus", true, TimeSpan.FromMilliseconds(50)); var subscrQueue = new QueuedHandlerThreadPool(subscrBus, "Subscriptions", false); _mainBus.Subscribe(subscrQueue.WidenFrom <SystemMessage.SystemStart, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <SystemMessage.BecomeShuttingDown, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <TcpMessage.ConnectionClosed, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <ClientMessage.SubscribeToStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <ClientMessage.UnsubscribeFromStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <SubscriptionMessage.PollStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <SubscriptionMessage.CheckPollTimeout, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom <StorageMessage.EventCommitted, Message>()); var subscription = new SubscriptionsService(_mainQueue, subscrQueue, readIndex); subscrBus.Subscribe <SystemMessage.SystemStart>(subscription); subscrBus.Subscribe <SystemMessage.BecomeShuttingDown>(subscription); subscrBus.Subscribe <TcpMessage.ConnectionClosed>(subscription); subscrBus.Subscribe <ClientMessage.SubscribeToStream>(subscription); subscrBus.Subscribe <ClientMessage.UnsubscribeFromStream>(subscription); subscrBus.Subscribe <SubscriptionMessage.PollStream>(subscription); subscrBus.Subscribe <SubscriptionMessage.CheckPollTimeout>(subscription); subscrBus.Subscribe <StorageMessage.EventCommitted>(subscription); // PERSISTENT SUBSCRIPTIONS // IO DISPATCHER var ioDispatcher = new IODispatcher(_mainQueue, new PublishEnvelope(_mainQueue)); _mainBus.Subscribe <ClientMessage.ReadStreamEventsBackwardCompleted>(ioDispatcher.BackwardReader); _mainBus.Subscribe <ClientMessage.WriteEventsCompleted>(ioDispatcher.Writer); _mainBus.Subscribe <ClientMessage.ReadStreamEventsForwardCompleted>(ioDispatcher.ForwardReader); _mainBus.Subscribe <ClientMessage.DeleteStreamCompleted>(ioDispatcher.StreamDeleter); _mainBus.Subscribe(ioDispatcher); var perSubscrBus = new InMemoryBus("PersistentSubscriptionsBus", true, TimeSpan.FromMilliseconds(50)); var perSubscrQueue = new QueuedHandlerThreadPool(perSubscrBus, "PersistentSubscriptions", false); _mainBus.Subscribe(perSubscrQueue.WidenFrom <SystemMessage.StateChangeMessage, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <TcpMessage.ConnectionClosed, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.CreatePersistentSubscription, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.UpdatePersistentSubscription, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.DeletePersistentSubscription, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.ConnectToPersistentSubscription, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.UnsubscribeFromStream, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.PersistentSubscriptionAckEvents, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.PersistentSubscriptionNackEvents, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.ReplayAllParkedMessages, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.ReplayParkedMessage, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <ClientMessage.ReadNextNPersistentMessages, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <StorageMessage.EventCommitted, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <MonitoringMessage.GetAllPersistentSubscriptionStats, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <MonitoringMessage.GetStreamPersistentSubscriptionStats, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <MonitoringMessage.GetPersistentSubscriptionStats, Message>()); _mainBus.Subscribe(perSubscrQueue.WidenFrom <SubscriptionMessage.PersistentSubscriptionTimerTick, Message>()); //TODO CC can have multiple threads working on subscription if partition var consumerStrategyRegistry = new PersistentSubscriptionConsumerStrategyRegistry(_mainQueue, _mainBus, vNodeSettings.AdditionalConsumerStrategies); var persistentSubscription = new PersistentSubscriptionService(subscrQueue, readIndex, ioDispatcher, _mainQueue, consumerStrategyRegistry); perSubscrBus.Subscribe <SystemMessage.BecomeShuttingDown>(persistentSubscription); perSubscrBus.Subscribe <SystemMessage.BecomeMaster>(persistentSubscription); perSubscrBus.Subscribe <SystemMessage.StateChangeMessage>(persistentSubscription); perSubscrBus.Subscribe <TcpMessage.ConnectionClosed>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.ConnectToPersistentSubscription>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.UnsubscribeFromStream>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.PersistentSubscriptionAckEvents>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.PersistentSubscriptionNackEvents>(persistentSubscription); perSubscrBus.Subscribe <StorageMessage.EventCommitted>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.DeletePersistentSubscription>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.CreatePersistentSubscription>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.UpdatePersistentSubscription>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.ReplayAllParkedMessages>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.ReplayParkedMessage>(persistentSubscription); perSubscrBus.Subscribe <ClientMessage.ReadNextNPersistentMessages>(persistentSubscription); perSubscrBus.Subscribe <MonitoringMessage.GetAllPersistentSubscriptionStats>(persistentSubscription); perSubscrBus.Subscribe <MonitoringMessage.GetStreamPersistentSubscriptionStats>(persistentSubscription); perSubscrBus.Subscribe <MonitoringMessage.GetPersistentSubscriptionStats>(persistentSubscription); perSubscrBus.Subscribe <SubscriptionMessage.PersistentSubscriptionTimerTick>(persistentSubscription); // STORAGE SCAVENGER var storageScavenger = new StorageScavenger(db, ioDispatcher, tableIndex, hash, readIndex, Application.IsDefined(Application.AlwaysKeepScavenged), _nodeInfo.ExternalHttp.ToString(), !vNodeSettings.DisableScavengeMerging, vNodeSettings.ScavengeHistoryMaxAge); // ReSharper disable RedundantTypeArgumentsOfMethod _mainBus.Subscribe <ClientMessage.ScavengeDatabase>(storageScavenger); _mainBus.Subscribe <UserManagementMessage.UserManagementServiceInitialized>(storageScavenger); // ReSharper restore RedundantTypeArgumentsOfMethod // TIMER _timeProvider = new RealTimeProvider(); _timerService = new TimerService(new ThreadBasedScheduler(_timeProvider)); _mainBus.Subscribe <SystemMessage.BecomeShutdown>(_timerService); _mainBus.Subscribe <TimerMessage.Schedule>(_timerService); var gossipInfo = new VNodeInfo(_nodeInfo.InstanceId, _nodeInfo.DebugIndex, vNodeSettings.GossipAdvertiseInfo.InternalTcp, vNodeSettings.GossipAdvertiseInfo.InternalSecureTcp, vNodeSettings.GossipAdvertiseInfo.ExternalTcp, vNodeSettings.GossipAdvertiseInfo.ExternalSecureTcp, vNodeSettings.GossipAdvertiseInfo.InternalHttp, vNodeSettings.GossipAdvertiseInfo.ExternalHttp); if (!isSingleNode) { // MASTER REPLICATION var masterReplicationService = new MasterReplicationService(_mainQueue, gossipInfo.InstanceId, db, _workersHandler, epochManager, vNodeSettings.ClusterNodeCount); _mainBus.Subscribe <SystemMessage.SystemStart>(masterReplicationService); _mainBus.Subscribe <SystemMessage.StateChangeMessage>(masterReplicationService); _mainBus.Subscribe <ReplicationMessage.ReplicaSubscriptionRequest>(masterReplicationService); _mainBus.Subscribe <ReplicationMessage.ReplicaLogPositionAck>(masterReplicationService); monitoringInnerBus.Subscribe <ReplicationMessage.GetReplicationStats>(masterReplicationService); // REPLICA REPLICATION var replicaService = new ReplicaService(_mainQueue, db, epochManager, _workersHandler, _internalAuthenticationProvider, gossipInfo, vNodeSettings.UseSsl, vNodeSettings.SslTargetHost, vNodeSettings.SslValidateServer, vNodeSettings.IntTcpHeartbeatTimeout, vNodeSettings.ExtTcpHeartbeatInterval); _mainBus.Subscribe <SystemMessage.StateChangeMessage>(replicaService); _mainBus.Subscribe <ReplicationMessage.ReconnectToMaster>(replicaService); _mainBus.Subscribe <ReplicationMessage.SubscribeToMaster>(replicaService); _mainBus.Subscribe <ReplicationMessage.AckLogPosition>(replicaService); _mainBus.Subscribe <StorageMessage.PrepareAck>(replicaService); _mainBus.Subscribe <StorageMessage.CommitAck>(replicaService); _mainBus.Subscribe <ClientMessage.TcpForwardMessage>(replicaService); } // ELECTIONS var electionsService = new ElectionsService(_mainQueue, gossipInfo, vNodeSettings.ClusterNodeCount, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint, epochManager, () => readIndex.LastCommitPosition, vNodeSettings.NodePriority); electionsService.SubscribeMessages(_mainBus); if (!isSingleNode) { // GOSSIP var gossip = new NodeGossipService(_mainQueue, gossipSeedSource, gossipInfo, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint, epochManager, () => readIndex.LastCommitPosition, vNodeSettings.NodePriority, vNodeSettings.GossipInterval, vNodeSettings.GossipAllowedTimeDifference); _mainBus.Subscribe <SystemMessage.SystemInit>(gossip); _mainBus.Subscribe <GossipMessage.RetrieveGossipSeedSources>(gossip); _mainBus.Subscribe <GossipMessage.GotGossipSeedSources>(gossip); _mainBus.Subscribe <GossipMessage.Gossip>(gossip); _mainBus.Subscribe <GossipMessage.GossipReceived>(gossip); _mainBus.Subscribe <SystemMessage.StateChangeMessage>(gossip); _mainBus.Subscribe <GossipMessage.GossipSendFailed>(gossip); _mainBus.Subscribe <SystemMessage.VNodeConnectionEstablished>(gossip); _mainBus.Subscribe <SystemMessage.VNodeConnectionLost>(gossip); } _workersHandler.Start(); _mainQueue.Start(); monitoringQueue.Start(); subscrQueue.Start(); if (subsystems != null) { foreach (var subsystem in subsystems) { var http = isSingleNode ? new [] { _externalHttpService } : new [] { _internalHttpService, _externalHttpService }; subsystem.Register(new StandardComponents(db, _mainQueue, _mainBus, _timerService, _timeProvider, httpSendService, http, _workersHandler)); } } }
/// <summary> /// Initializes a new instance of the <see cref="DefaultPrivacyProvider"/> class. /// </summary> /// <param name="authentication">Authentication provider.</param> public DefaultPrivacyProvider(IAuthenticationProvider authentication) { AuthenticationProvider = authentication; }
private void AuthenticationProvider_OnAuthenticationFailed(IAuthenticationProvider provider, string reason) { AddText(string.Format("Authentication Failed! Reason: '{0}'", reason)); }
public HomeController(IAuthenticationProvider authSettings, ILogger <HomeController> logger) { this.authSettings = authSettings; this.logger = logger; }
public DigitServiceClient(IAuthenticationProvider authenticationProvider, IOptions <DigitServiceOptions> optionsAccessor) { options = optionsAccessor.Value; this.authenticationProvider = authenticationProvider; }