private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxEmail.Text.Length == 0)
            {
                errormessage.Text = "Enter an email.";
                textBoxEmail.Focus();
            }
            else if (!textBoxEmail.Text.Equals("1") && (!Regex.IsMatch(textBoxEmail.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$")))
            {
                errormessage.Text = "Enter a valid email.";
                textBoxEmail.Select(0, textBoxEmail.Text.Length);
                textBoxEmail.Focus();

            }
            else if ((comboBoxDatabase.SelectedValue as ListBoxItem) == null)
            {
                errormessage.Text = "Select database from provided list";
            }
            else
            {
                // Save global variables with connection string to database selected from combo for future nhibernate use when initiation session
                if ((comboBoxDatabase.SelectedValue as ListBoxItem).Content.ToString().Equals("mydb"))
                {
                    Application.Current.Properties["HOSTNAME"] = "localhost";
                    Application.Current.Properties["DBSID"] = "mydb";
                    Application.Current.Properties["DBUSER"] = "******";
                    Application.Current.Properties["DBPASSWORD"] = "******";
                }
                else if ((comboBoxDatabase.SelectedValue as ListBoxItem).Content.ToString().Equals("mydbTest"))
                {
                    Application.Current.Properties["HOSTNAME"] = "localhost";
                    Application.Current.Properties["DBSID"] = "mydbTest";
                    Application.Current.Properties["DBUSER"] = "******";
                    Application.Current.Properties["DBPASSWORD"] = "******";
                }

                string email = textBoxEmail.Text;
                string password = passwordBox1.Password;
                UserIdentity userInstance = new UserIdentity();

                bool isUserAuthenticated = nhibernategateway.ValidateUserCredentials(email,password, out userInstance);

                if (isUserAuthenticated)
                {
                    Application.Current.Properties["LoggedUserID"] = userInstance.id.ToString();
                    Application.Current.Properties["LoggedUserEmail"] = userInstance.email.ToString();

                    MainConsole myMainWindow = new MainConsole();
                    System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
                    System.Windows.Application.Current.MainWindow = myMainWindow;

                    myMainWindow.Show();
                    Close();
                }
                else
                {
                    errormessage.Text = "Please enter existing Email/Password.";
                }
            }
        }
 public void Terminate(UserIdentity userIdentity)
 {
     if (_serverSidePresentationSchemaTransfer.Contains(userIdentity))
         _serverSidePresentationSchemaTransfer.Terminate(userIdentity);
     else if (_serverSidePresentationTransfer.Contains(userIdentity))
         _serverSidePresentationTransfer.Terminate(userIdentity);
 }
Beispiel #3
0
        protected void btnLogon_Click(object sender, EventArgs e)
        {
            if (AuthMod.ValidateUser(txtInputBrukernavn.Text, txtInputPassord.Text)) {
            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, txtInputBrukernavn.Text, DateTime.Now,
               DateTime.Now.AddMinutes(30), chkRememberMe.Checked, "AuthentiCationCookie");
            string cookiestr = FormsAuthentication.Encrypt(tkt);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            if (chkRememberMe.Checked)
               authCookie.Expires = tkt.Expiration;
            authCookie.Path = FormsAuthentication.FormsCookiePath;

            string encTicket = authCookie.Value;
            if (!String.IsNullOrEmpty(encTicket)) {
               var ticket = FormsAuthentication.Decrypt(encTicket);
               UserIdentity id = new UserIdentity(ticket, AuthMod);
               var userRoles = AuthMod.GetRolesForUser(id.Name);
               var prin = new GenericPrincipal(id, userRoles);
               HttpContext.Current.User = prin;
            }
            System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;
            HttpContext.Current.Cache.Insert("customPrincipal", HttpContext.Current.User);

            Response.Cookies.Add(authCookie);
            FormsAuthentication.RedirectFromLoginPage(txtInputBrukernavn.Text, chkRememberMe.Checked);
             } else {
            logonErrorSpan.Visible = true;
            //Response.Redirect("~/Public/Login.aspx", true);
             }
        }
Beispiel #4
0
 private void _lockingStorage_OnRemoveItem(UserIdentity sender, ObjectKey key, LockingInfoWithCommunicationObject value)
 {
     if (RemoveItem != null)
     {
         RemoveItem(sender, key, value.LockingInfo);
     }
 }
 public FileTransferObject? Receive(UserIdentity userIdentity, string resourceId)
 {
     if (_serverSidePresentationSchemaTransfer.Contains(userIdentity))
         return _serverSidePresentationSchemaTransfer.Receive(userIdentity, resourceId);
     else if (_serverSidePresentationTransfer.Contains(userIdentity))
         return _serverSidePresentationTransfer.Receive(userIdentity, resourceId);
     return null;
 }
 public FileSaveStatus Send(UserIdentity userIdentity, FileTransferObject obj)
 {
     if (_serverSidePresentationSchemaTransfer.Contains(userIdentity))
         return _serverSidePresentationSchemaTransfer.Send(userIdentity, obj);
     else if (_serverSidePresentationTransfer.Contains(userIdentity))
         return _serverSidePresentationTransfer.Send(userIdentity, obj);
     return FileSaveStatus.Abort;
 }
Beispiel #7
0
            // deauthenticates the user given by the input session
            public void Deauthenticate(ref UserSession session)
            {
                // gets the sessions authenticated id (possibly null)
                var authenticatedId = session?.Identity().AuthenticatedId;
                if (authenticatedId == null) return;

                // deauthenticates the current user
                var userId = new UserIdentity(authenticatedId.GetValueOrDefault(), "");
                session = new UserSession(userId, false);
            }
        public int MapIdentity(string userid, string identytProvider, string identityValue)
        {
            var mapping = new UserIdentity();
            mapping.UserId = new Guid(userid);
            mapping.IdentityProvider = identytProvider;
            mapping.IdentityValue = identityValue;
            _context.AddToUserIdentities(mapping);
            _context.SaveChanges();

            return mapping.IdentityID;
        }
 public FileTransferObject? Receive(UserIdentity userIdentity, string resourceId)
 {
     try
     {
         return _serverSideGroupFileTransfer.Receive(userIdentity, resourceId);
     }
     catch(Exception ex)
     {
         _config.EventLog.WriteError(string.Format("ConfigurationExportHelper.Receive: {0}", ex));
         return null;
     }
 }
Beispiel #10
0
        //private readonly LockingNotifier _notifier = new LockingNotifier();

        public LockingService(UserIdentity systemUser, IEventLogging log)
        {
            _systemUser = systemUser;
            _log = log;
            _timer = new Timer(_interval);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();
            _lockingStorage = new LockingStorage();
            _lockingStorage.OnAddItem += _lockingStorage_OnAddItem;
            _lockingStorage.OnRemoveItem += _lockingStorage_OnRemoveItem;
            //_lockingStorage.OnAddItem += new TechnicalServices.Common.StorageAction<ObjectKey, LockingInfo>(_notifier.SubscribeForMonitor);
            //_lockingStorage.OnRemoveItem +=new TechnicalServices.Common.StorageAction<ObjectKey,LockingInfo>(_notifier.UnSubscribeForMonitor);
        }
        public ServerSideFileReceive(UserIdentity userIdentity, /*IResourceEx<T> resourceEx*/IFileInfoProvider provider)
        {
            //_resourceEx = resourceEx;
            _userIdentity = userIdentity;
            //Resource = resource;
            _provider = provider;
            //_resourceFileInfo = _resource.ResourceInfo as ResourceFileInfo;
            if (OperationContext.Current != null && OperationContext.Current.Channel != null)
            {
                _communicationObject = OperationContext.Current.Channel;
                _communicationObject.Faulted += new EventHandler(Abort);
            }

        }
Beispiel #12
0
            // authenticates and provides a user with a corresponding session
            public UserSession Authenticate(string email, string password)
            {
                // returns null if user could not be authenticated based on the input   
                using (var db = new SmartPoolContext())
                {
                    // queries the database for users with the specified input
                    var userQuery = from users in db.Users
                        where users.Email == email && users.Password == password
                        select users.UserId;

                    // checks to see whether the input was matched by the query
                    var userId = new UserIdentity(userQuery.First(), password);
                    return userQuery.Any() ? new UserSession(userId, true) : null;
                }
            }
        public PresentationListController(PresentationListForm AView)
        {
            _instance = this;
            view = AView;

            identity = Thread.CurrentPrincipal as UserIdentity;

            DesignerClient.Instance.PresentationNotifier.OnObjectLocked += new EventHandler<NotifierEventArg<LockingInfo>>(PresentationNotifier_OnObjectLocked);
            DesignerClient.Instance.PresentationNotifier.OnObjectUnLocked += new EventHandler<NotifierEventArg<LockingInfo>>(PresentationNotifier_OnObjectUnLocked);
            DesignerClient.Instance.PresentationNotifier.OnPresentationAdded += new EventHandler<NotifierEventArg<PresentationInfo>>(PresentationNotifier_OnPresentationAdded);
            DesignerClient.Instance.PresentationNotifier.OnPresentationDeleted += new EventHandler<NotifierEventArg<PresentationInfo>>(PresentationNotifier_OnPresentationDeleted);
            DesignerClient.Instance.PresentationNotifier.OnObjectChanged += new EventHandler<NotifierEventArg<IList<ObjectInfo>>>(PresentationNotifier_OnObjectChanged);

            DesignerClient.Instance.PresentationWorker.SubscribeForGlobalMonitoring();
        }
 public override bool DeleteSource(UserIdentity sender, DeviceResourceDescriptor descriptor)
 {
     _sync.AcquireWriterLock(Timeout.Infinite);
     try
     {
         bool isSuccess = base.DeleteSource(sender, descriptor);
         if (isSuccess)
             _cache.DeleteResource(descriptor);
         return isSuccess;
     }
     finally
     {
         _sync.ReleaseWriterLock();
     }
 }
        public override bool DeletePresentation(UserIdentity sender, string uniqueName)
        {
            _sync.AcquireWriterLock(Timeout.Infinite);
            try
            {
                bool isSuccess = base.DeletePresentation(sender, uniqueName);
                if (isSuccess)
                    _cache.Delete(ObjectKeyCreator.CreatePresentationKey(uniqueName));
                return isSuccess;
            }
            finally
            {
                _sync.ReleaseWriterLock();
            }

        }
 public override bool SavePresentation(UserIdentity sender, Presentation presentation)
 {
     _sync.AcquireWriterLock(Timeout.Infinite);
     try
     {
         bool isSuccess = base.SavePresentation(sender, presentation);
         if (isSuccess)
             _cache.Add(ObjectKeyCreator.CreatePresentationKey(presentation),
                 presentation);
         return isSuccess;
     }
     finally
     {
         _sync.ReleaseWriterLock();
     }
 }
        /// <summary>
        /// Authenticate the request.
        /// Using Custom Forms Authentication since I'm not using the "RolesProvider".
        /// Roles are manually stored / encrypted in a cookie in <see cref="FormsAuthenticationService.SignIn"/>
        /// This takes out the roles from the cookie and rebuilds the Principal w/ the decrypted roles.
        /// http://msdn.microsoft.com/en-us/library/aa302397.aspx
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void RebuildUserFromCookies()
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
            if (null == authCookie) return;

            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            String[] roles = authTicket.UserData.Split(new char[] { ',' });

            // Create an Identity object
            IIdentity id = new UserIdentity(0, authTicket.Name, "Forms", true);
            IPrincipal principal = new UserPrincipal(0, authTicket.Name, roles, id);

            // Attach the new principal object to the current HttpContext object
            HttpContext.Current.User = principal;
        }
 public void LoginStatusChange(UserIdentity user, LogOnStatus newLoginStatus)
 {
     switch (newLoginStatus)
     {
         case LogOnStatus.LogOn:
             _list.Add(user);
             break;
         case LogOnStatus.LogOff:
             //int index = _list. FindIndex(value => value.Name == user.Name);
             //if (index >= 0)
             //    _list.RemoveAt(index);
             _list.Remove(user);
             break;
         default:
             throw new ApplicationException("Ненене Дэвид Блейн ненене");
     }
 }
        public static string GetPresentationStatusDescr(string Name, PresentationStatus status, UserIdentity id)
        {
            StringBuilder sb = new StringBuilder();
            string userName = string.Empty;
            if ((id != null) && (id.User != null))
                userName = string.IsNullOrEmpty(id.User.FullName) ? id.User.Name : id.User.FullName;
            switch (status)
            {
                case PresentationStatus.Deleted: sb.Append("Сценарий уже удален"); break;
                case PresentationStatus.LockedForEdit: sb.AppendFormat("Сценарий заблокирован пользователем {0} для редактирования", userName); break;
                case PresentationStatus.LockedForShow: sb.AppendFormat("Сценарий заблокирован пользователем {0} для показа", userName); break;
                case PresentationStatus.SlideLocked: sb.Append("Сцена сценария заблокирована"); break;
                case PresentationStatus.Unknown: sb.Append("Неизвестно"); break;
                case PresentationStatus.AlreadyLocallyOpened: sb.Append("Сценарий уже открыт в другом экземпляре Дизайнера"); break;
            }

            return sb.ToString();
        }
        public override DeviceResourceDescriptor SaveSource(UserIdentity sender, DeviceResourceDescriptor resourceDescriptor, Dictionary<string, string> fileDic)
        {
            _sync.AcquireWriterLock(Timeout.Infinite);
            try
            {

                DeviceResourceDescriptor stored
                    = base.SaveSource(sender, resourceDescriptor, fileDic);
                if (null != stored)
                {
                    _cache.AddResource(stored);
                }
                return stored;
            }
            finally
            {
                _sync.ReleaseWriterLock();
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new UserIdentity(model.UserName);
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #22
0
        public void TestIdentityConstruction()
        {
            // Arrange
            string testIdentityString = string.Format("{0}{2}{1}", Provider, Identity, UserIdentity.IdentitySeparator);
            UserIdentity userIdentity = null;

            // Act
            try
            {
                userIdentity = new UserIdentity(testIdentityString);
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }

            // Assert
            Assert.IsNotNull(userIdentity);
            Assert.AreEqual(userIdentity.IdentityProvider, IdentityProviderType.Email);
            Assert.AreEqual(userIdentity.IdentityValue, Identity);
        }
 public BackgroundPresentationManager(IServerConfiguration config,
     IPresentationWorker worker,
     PresentationShowPreparator preparator,
     DisplayAndEquipmentMonitor monitor,
     IShowDisplayAndDeviceCommand showDisplayAndDeviceCommand,
     UserIdentity systemUser)
 {
     _config = config;
     _showPreparator = preparator;
     _monitor = monitor;
     _worker = worker;
     _showDisplayAndDeviceCommand = showDisplayAndDeviceCommand;
     _systemUser = systemUser;
     _restoreShowTimer = new Timer(RestoreShow);
     TimeSpan interval =TimeSpan.FromSeconds(BackgroundPresentationRestoreTimeout);
     _backgroundPresentationChange = new Timer(MonitorForBackgroundPresentation, null, interval, interval);
     // мониторинг оборудования
     _monitor.OnStateChange += new EventHandler<TechnicalServices.Interfaces.ConfigModule.Server.EqiupmentStateChangeEventArgs>(_monitor_OnStateChange);
     // мониторинг изменения в фоновом сценарии
     _worker.OnPresentationChanged += new EventHandler<PresentationChangedEventArgs>(_worker_OnPresentationChanged);
 }
        public async Task<ActionResult> Register(RegisterViewModel model, string redirectUrl)
        {
            if (ModelState.IsValid)
            { 
                if (_userService.CheckEmail(model.Email))
                {
                    ModelState.AddModelError("", "This Email is already occupied. Please enter another Email!");
                }
                else
                {
                    var user = new UserIdentity {UserName = model.Name, Email = model.Email};
                    var result = await _userManager.CreateAsync(user, model.Password);
                    if (result == IdentityResult.Success)
                    {
                        user = await _userManager.FindByNameAsync(model.Email);
                        await SignInAsync(user, true);
                        return RedirectToAction("Inbox", "Lists");
                    }
                }
            }

            return View(model);
        }
Beispiel #25
0
        public void TestIdentityConstructionFromEncodedString()
        {
            // Arrange
            string encodedString = Convert.ToBase64String(Encoding.UTF8.GetBytes(Identity));

            string testIdentityString = string.Format("{0}{2}{1}", Provider, encodedString, UserIdentity.IdentitySeparator);
            UserIdentity userIdentity = null;

            // Act
            try
            {
                userIdentity = new UserIdentity(testIdentityString, true);
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }

            // Assert
            Assert.IsNotNull(userIdentity);
            Assert.AreEqual(userIdentity.IdentityProvider, IdentityProviderType.Email);
            Assert.AreEqual(userIdentity.IdentityValue, Identity);
            Assert.AreEqual(userIdentity.EncodedIdentity, testIdentityString);
        }
        public bool CreateFormsAuthenticationTicket(string loginName, AuthenticateUserResponse response)
        {
            // If we got here, we are authorized. Let's attempt to get the identity.
            var identity = new UserIdentity
            {
                FirstName = response.FirstName,
                LastName = response.LastName,
                LoginName = loginName
            };

            // Create the ticket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                GlobalSettings.Exigo.Api.CompanyKey + "_" + loginName,
                DateTime.Now,
                DateTime.Now.AddMinutes(GlobalSettings.Backoffices.SessionTimeout),
                false,
                identity.SerializeProperties());

            // Encrypt the ticket
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie.
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; //saved user
            if (cookie == null)
            {
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
            }
            else
            {
                cookie.Value = encTicket;
                HttpContext.Current.Response.Cookies.Set(cookie);
            }

            return true;
        }
 public dynamic obterTrilhaTutorialPorCategoriaIdPaginado(int categoriaId, int tutorialId, UserIdentity usuarioLogado)
 {
     return(bmTrilhaTutorial.obterTrilhaTutorialPorCategoriaIdPaginado(categoriaId, tutorialId, usuarioLogado.Usuario.ID, usuarioLogado.Nivel));
 }
Beispiel #28
0
        public async Task FlowWithInvalidTypeInputValidationShouldFailAndNotChangeStateProperly()
        {
            // Arrange
            var input = new PlainText()
            {
                Text = "Ping!"
            };

            Message.Content = input;
            var invalidInputMessage = new Message()
            {
                From    = UserIdentity.ToNode(),
                To      = ApplicationIdentity.ToNode(),
                Content = new MediaLink()
            };
            var messageType              = "text/plain";
            var messageContent           = "Pong!";
            var validationMessageContent = "Invalid message type";

            var flow = new Flow()
            {
                Id     = Guid.NewGuid().ToString(),
                States = new[]
                {
                    new State
                    {
                        Id    = "root",
                        Root  = true,
                        Input = new Input
                        {
                            Validation = new InputValidation
                            {
                                Rule  = InputValidationRule.Type,
                                Type  = PlainText.MediaType,
                                Error = validationMessageContent
                            }
                        },
                        Outputs = new[]
                        {
                            new Output
                            {
                                StateId = "ping"
                            }
                        }
                    },
                    new State
                    {
                        Id           = "ping",
                        InputActions = new[]
                        {
                            new Action
                            {
                                Type     = "SendMessage",
                                Settings = new JObject()
                                {
                                    { "type", messageType },
                                    { "content", messageContent }
                                }
                            }
                        }
                    }
                }
            };
            var target = GetTarget();

            // Act
            await target.ProcessInputAsync(invalidInputMessage, flow, CancellationToken);

            await target.ProcessInputAsync(Message, flow, CancellationToken);

            // Assert
            StateManager.Received(1).SetStateIdAsync(Context, "ping", Arg.Any <CancellationToken>());
            StateManager.Received(1).DeleteStateIdAsync(Context, Arg.Any <CancellationToken>());
            Sender
            .Received(1)
            .SendMessageAsync(
                Arg.Is <Message>(m =>
                                 m.Id != null &&
                                 m.To.ToIdentity().Equals(UserIdentity) &&
                                 m.Type.ToString().Equals(messageType) &&
                                 m.Content.ToString() == validationMessageContent),
                Arg.Any <CancellationToken>());
            Sender
            .Received(1)
            .SendMessageAsync(
                Arg.Is <Message>(m =>
                                 m.Id != null &&
                                 m.To.ToIdentity().Equals(UserIdentity) &&
                                 m.Type.ToString().Equals(messageType) &&
                                 m.Content.ToString() == messageContent),
                Arg.Any <CancellationToken>());
        }
Beispiel #29
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new UserIdentity {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
        private async Task <Session> ConsoleSampleClient()
        {
            var application = new ApplicationInstance {
                ApplicationType = ApplicationType.Client
            };

            #region Create an Application Configuration
            Console.WriteLine(" 1 - Create an Application Configuration.");
            ExitCode = ExitCode.ErrorCreateApplication;

            // Load the Application Configuration and use the specified config section "Technosoftware.SimpleClient"
            var config = await application.LoadConfigurationAsync("Technosoftware.SimpleClient");

            // check the application certificate.
            var haveAppCertificate = await application.CheckApplicationInstanceCertificateAsync(false, CertificateFactory.DefaultKeySize, CertificateFactory.DefaultLifeTime);

            reverseConnectManager_ = null;
            if (ReverseConnectUri != null)
            {
                // start the reverse connection manager
                reverseConnectManager_ = new ReverseConnectManager();
                reverseConnectManager_.AddEndpoint(ReverseConnectUri);
                reverseConnectManager_.StartService(config);
            }

            if (haveAppCertificate)
            {
                config.ApplicationUri = X509Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate);
                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    autoAccept_ = true;
                }
                config.CertificateValidator.CertificateValidation += OnCertificateValidation;
            }
            else
            {
                Console.WriteLine("    WARN: missing application certificate, using unsecured connection.");
            }
            #endregion

            #region Discover endpoints
            Console.WriteLine(" 2 - Discover endpoints of {0}.", endpointUrl_);
            ExitCode = ExitCode.ErrorDiscoverEndpoints;
            EndpointDescription selectedEndpoint;
            if (reverseConnectManager_ == null)
            {
                selectedEndpoint = Discover.SelectEndpoint(endpointUrl_, haveAppCertificate && !SecurityNone, 15000);
            }
            else
            {
                Console.WriteLine("   Waiting for reverse connection.");
                var connection = await reverseConnectManager_.WaitForConnection(
                    new Uri(endpointUrl_), null, new CancellationTokenSource(60000).Token);

                if (connection == null)
                {
                    throw new ServiceResultException(StatusCodes.BadTimeout, "Waiting for a reverse connection timed out.");
                }
                selectedEndpoint = Discover.SelectEndpoint(config, connection, haveAppCertificate && !SecurityNone, 15000);
            }

            Console.WriteLine("    Selected endpoint uses: {0}",
                              selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1));
            #endregion

            #region Create a session with OPC UA server
            Console.WriteLine(" 3 - Create a session with OPC UA server.");
            ExitCode = ExitCode.ErrorCreateSession;

            // create the user identity
            UserIdentity userIdentity;
            if (String.IsNullOrEmpty(Username) && String.IsNullOrEmpty(Password))
            {
                userIdentity = new UserIdentity(new AnonymousIdentityToken());
            }
            else
            {
                userIdentity = new UserIdentity(Username, Password);
            }

            // create worker session
            if (reverseConnectManager_ == null)
            {
                session_ = await CreateSessionAsync(config, selectedEndpoint, userIdentity).ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine("   Waiting for reverse connection.");
                // Define the cancellation token.
                var source = new CancellationTokenSource(60000);
                var token  = source.Token;
                try
                {
                    var connection = await reverseConnectManager_.WaitForConnection(
                        new Uri(endpointUrl_), null, token);

                    if (connection == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadTimeout,
                                                         "Waiting for a reverse connection timed out.");
                    }

                    session_ = await CreateSessionAsync(config, connection, selectedEndpoint, userIdentity)
                               .ConfigureAwait(false);
                }
                finally
                {
                    source.Dispose();
                }
            }

            // register keep alive handler
            session_.SessionKeepAliveEvent += OnSessionKeepAliveEvent;
            #endregion

            #region Browse the OPC UA Server
            Console.WriteLine(" 4 - Browse address space.");
            // Create the browser
            var browser = new Browser(session_)
            {
                BrowseDirection   = BrowseDirection.Forward,
                ReferenceTypeId   = ReferenceTypeIds.HierarchicalReferences,
                IncludeSubtypes   = true,
                NodeClassMask     = 0,
                ContinueUntilDone = false
            };

            // Browse from the RootFolder
            var references = browser.Browse(Objects.ObjectsFolder);

            GetElements(session_, browser, 0, references, Verbose);

            #endregion

            #region Read a single value
            Console.WriteLine(" 5 - Read a single value.");
            var simulatedDataValue = session_.ReadValue(simulatedDataNodeId_);
            Console.WriteLine("Node Value:" + simulatedDataValue.Value);
            #endregion

            #region Read multiple values
            Console.WriteLine(" 6 - Read multiple values.");
            // The input parameters of the ReadValues() method
            var variableIds   = new List <NodeId>();
            var expectedTypes = new List <Type>();

            // Add a node to the list
            variableIds.Add(simulatedDataNodeId_);
            // Add an expected type to the list (null means we get the original type from the server)
            expectedTypes.Add(null);

            // Add another node to the list
            variableIds.Add(staticDataNodeId1_);
            // Add an expected type to the list (null means we get the original type from the server)
            expectedTypes.Add(null);

            // Add another node to the list
            variableIds.Add(staticDataNodeId2_);

            // Add an expected type to the list (null means we get the original type from the server)
            expectedTypes.Add(null);

            session_.ReadValues(variableIds, expectedTypes, out var values, out var errors);
            // write the result to the console.
            for (var i = 0; i < values.Count; i++)
            {
                Console.WriteLine("Status of Read of Node {0} is: {1}", variableIds[i].ToString(), errors[i]);
            }
            for (var i = 0; i < values.Count; i++)
            {
                Console.WriteLine("Value of Read of Node {0} is: Value: {1}", variableIds[i].ToString(), values[i]);
            }
            #endregion

            #region Read multiple values asynchronous
            Console.WriteLine(" 7 - Read multiple values asynchronous.");
            // start reading the value (setting a 10 second timeout).
            session_.BeginReadValues(
                variableIds,
                0,
                TimestampsToReturn.Both,
                OnReadComplete,
                new UserData {
                Session = session_, NodeIds = variableIds
            });
            #endregion

            #region Write a value
            Console.WriteLine(" 8 - Write a value.");
            short writeInt = 1234;

            Console.WriteLine("Write Value: " + writeInt);
            session_.WriteValue(staticDataNodeId1_, new DataValue(writeInt));

            // read it again to check the new value
            Console.WriteLine("Node Value (should be {0}): {1}", session_.ReadValue(staticDataNodeId1_).Value, writeInt);
            #endregion

            #region Write multiple values at once
            Console.WriteLine(" 9 - Write multiple values at once.");

            writeInt = 5678;
            var writeDouble = 1234.1234;

            var nodeIds    = new List <NodeId>();
            var dataValues = new List <DataValue>();

            nodeIds.Add(staticDataNodeId1_);
            nodeIds.Add(staticDataNodeId2_);

            dataValues.Add(new DataValue(writeInt));
            dataValues.Add(new DataValue(writeDouble));

            Console.WriteLine("Write Values: {0} and {1}", writeInt, writeDouble);
            var statusCodes = session_.WriteValues(nodeIds, dataValues);

            Console.WriteLine("Returned status codes:");
            foreach (var statusCode in statusCodes)
            {
                Console.WriteLine("Status: {0}", statusCode.ToString());
            }

            // read it again to check the new value
            Console.WriteLine("Node Value (should be {0}): {1}", session_.ReadValue(staticDataNodeId1_).Value, writeInt);
            Console.WriteLine("Node Value (should be {0}): {1}", session_.ReadValue(staticDataNodeId2_).Value, writeDouble);
            #endregion

            #region Write multiple values asynchronous
            Console.WriteLine("10 - Write multiple values asynchronous.");

            // start writing the values.
            session_.BeginWriteValues(
                nodeIds,
                dataValues,
                OnWriteComplete,
                new UserData {
                Session = session_, NodeIds = nodeIds
            });
            #endregion

            #region Call a Method
            Console.WriteLine("11 - Call a Method.");
            INode node = session_.ReadNode(callHelloMethodNodeId_);


            if (node is MethodNode)
            {
                var methodId = callHelloMethodNodeId_;

                var objectId = methodsNodeId_;

                var inputArguments = new VariantCollection {
                    new Variant("from Technosoftware")
                };

                var request = new CallMethodRequest {
                    ObjectId = objectId, MethodId = methodId, InputArguments = inputArguments
                };

                var requests = new CallMethodRequestCollection {
                    request
                };

                var responseHeader = session_.Call(
                    null,
                    requests,
                    out var results,
                    out var diagnosticInfos);

                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos,
                                                                       responseHeader.StringTable));
                }

                Console.WriteLine("{0}", results[0].OutputArguments[0]);
            }

            #endregion

            #region Create a subscription with publishing interval of 1 second
            Console.WriteLine("12 - Create a subscription with publishing interval of 1 second.");
            ExitCode      = ExitCode.ErrorCreateSubscription;
            subscription_ = new Subscription(session_.DefaultSubscription)
            {
                PublishingInterval = 1000
            };
            #endregion

            #region Add all dynamic values and the server time to the subscription
            Console.WriteLine("13 - Add all dynamic values and the server time to the subscription.");
            ExitCode = ExitCode.ErrorMonitoredItem;
            var list = new List <MonitoredItem> {
                new MonitoredItem(subscription_.DefaultItem)
                {
                    DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=" + Variables.Server_ServerStatus_CurrentTime
                }
            };
            list.ForEach(i => i.MonitoredItemNotificationEvent += OnNotification);

            var newItem = new MonitoredItem(subscription_.DefaultItem)
            {
                DisplayName = "Simulated Data Value",
                StartNodeId = new NodeId(simulatedDataNodeId_)
            };
            newItem.MonitoredItemNotificationEvent += OnMonitoredItemNotificationEvent;
            list.Add(newItem);

            subscription_.AddItems(list);
            #endregion

            #region Add the subscription to the session
            Console.WriteLine("14 - Add the subscription to the session.");
            ExitCode = ExitCode.ErrorAddSubscription;
            session_.AddSubscription(subscription_);
            subscription_.Create();
            #endregion

            #region Running...Press Ctrl-C to exit...
            Console.WriteLine("15 - Running...Press Ctrl-C to exit...");
            ExitCode = ExitCode.ErrorRunning;
            #endregion

            return(session_);
        }
Beispiel #31
0
        public Session(
            OperationContext context,
            IServerInternal server,
            X509Certificate2 serverCertificate,
            NodeId authenticationToken,
            byte[]                  serverNonce,
            string sessionName,
            ApplicationDescription clientDescription,
            string endpointUrl,
            X509Certificate2 clientCertificate,
            double sessionTimeout,
            uint maxResponseMessageSize,
            double maxRequestAge,
            int maxBrowseContinuationPoints,
            int maxHistoryContinuationPoints)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            // verify that a secure channel was specified.
            if (context.ChannelContext == null)
            {
                throw new ServiceResultException(StatusCodes.BadSecureChannelIdInvalid);
            }

            m_server = server;
            m_authenticationToken          = authenticationToken;
            m_serverNonce                  = serverNonce;
            m_sessionName                  = sessionName;
            m_serverCertificate            = serverCertificate;
            m_clientCertificate            = clientCertificate;
            m_secureChannelId              = context.ChannelContext.SecureChannelId;
            m_maxResponseMessageSize       = maxResponseMessageSize;
            m_maxRequestAge                = maxRequestAge;
            m_maxBrowseContinuationPoints  = maxBrowseContinuationPoints;
            m_maxHistoryContinuationPoints = maxHistoryContinuationPoints;
            m_endpoint = context.ChannelContext.EndpointDescription;

            // use anonymous the default identity.
            m_identity = new UserIdentity();

            // initialize diagnostics.
            m_diagnostics = new SessionDiagnosticsDataType();

            m_diagnostics.SessionId                          = null;
            m_diagnostics.SessionName                        = sessionName;
            m_diagnostics.ClientDescription                  = clientDescription;
            m_diagnostics.ServerUri                          = null;
            m_diagnostics.EndpointUrl                        = endpointUrl;
            m_diagnostics.LocaleIds                          = new StringCollection();
            m_diagnostics.ActualSessionTimeout               = sessionTimeout;
            m_diagnostics.ClientConnectionTime               = DateTime.UtcNow;
            m_diagnostics.ClientLastContactTime              = DateTime.UtcNow;
            m_diagnostics.CurrentSubscriptionsCount          = 0;
            m_diagnostics.CurrentMonitoredItemsCount         = 0;
            m_diagnostics.CurrentPublishRequestsInQueue      = 0;
            m_diagnostics.TotalRequestCount                  = new ServiceCounterDataType();
            m_diagnostics.UnauthorizedRequestCount           = 0;
            m_diagnostics.ReadCount                          = new ServiceCounterDataType();
            m_diagnostics.HistoryReadCount                   = new ServiceCounterDataType();
            m_diagnostics.WriteCount                         = new ServiceCounterDataType();
            m_diagnostics.HistoryUpdateCount                 = new ServiceCounterDataType();
            m_diagnostics.CallCount                          = new ServiceCounterDataType();
            m_diagnostics.CreateMonitoredItemsCount          = new ServiceCounterDataType();
            m_diagnostics.ModifyMonitoredItemsCount          = new ServiceCounterDataType();
            m_diagnostics.SetMonitoringModeCount             = new ServiceCounterDataType();
            m_diagnostics.SetTriggeringCount                 = new ServiceCounterDataType();
            m_diagnostics.DeleteMonitoredItemsCount          = new ServiceCounterDataType();
            m_diagnostics.CreateSubscriptionCount            = new ServiceCounterDataType();
            m_diagnostics.ModifySubscriptionCount            = new ServiceCounterDataType();
            m_diagnostics.SetPublishingModeCount             = new ServiceCounterDataType();
            m_diagnostics.PublishCount                       = new ServiceCounterDataType();
            m_diagnostics.RepublishCount                     = new ServiceCounterDataType();
            m_diagnostics.TransferSubscriptionsCount         = new ServiceCounterDataType();
            m_diagnostics.DeleteSubscriptionsCount           = new ServiceCounterDataType();
            m_diagnostics.AddNodesCount                      = new ServiceCounterDataType();
            m_diagnostics.AddReferencesCount                 = new ServiceCounterDataType();
            m_diagnostics.DeleteNodesCount                   = new ServiceCounterDataType();
            m_diagnostics.DeleteReferencesCount              = new ServiceCounterDataType();
            m_diagnostics.BrowseCount                        = new ServiceCounterDataType();
            m_diagnostics.BrowseNextCount                    = new ServiceCounterDataType();
            m_diagnostics.TranslateBrowsePathsToNodeIdsCount = new ServiceCounterDataType();
            m_diagnostics.QueryFirstCount                    = new ServiceCounterDataType();
            m_diagnostics.QueryNextCount                     = new ServiceCounterDataType();
            m_diagnostics.RegisterNodesCount                 = new ServiceCounterDataType();
            m_diagnostics.UnregisterNodesCount               = new ServiceCounterDataType();

            // initialize security diagnostics.
            m_securityDiagnostics = new SessionSecurityDiagnosticsDataType();

            m_securityDiagnostics.SessionId               = m_sessionId;
            m_securityDiagnostics.ClientUserIdOfSession   = m_identity.DisplayName;
            m_securityDiagnostics.AuthenticationMechanism = m_identity.TokenType.ToString();
            m_securityDiagnostics.Encoding = context.ChannelContext.MessageEncoding.ToString();

            m_securityDiagnostics.ClientUserIdHistory = new StringCollection();
            m_securityDiagnostics.ClientUserIdHistory.Add(m_identity.DisplayName);

            EndpointDescription description = context.ChannelContext.EndpointDescription;

            if (description != null)
            {
                m_securityDiagnostics.TransportProtocol = new Uri(description.EndpointUrl).Scheme;
                m_securityDiagnostics.SecurityMode      = m_endpoint.SecurityMode;
                m_securityDiagnostics.SecurityPolicyUri = m_endpoint.SecurityPolicyUri;
            }

            if (clientCertificate != null)
            {
                m_securityDiagnostics.ClientCertificate = clientCertificate.RawData;
            }

            ServerSystemContext systemContext = m_server.DefaultSystemContext.Copy(context);

            // create diagnostics object.
            m_sessionId = server.DiagnosticsNodeManager.CreateSessionDiagnostics(
                systemContext,
                m_diagnostics,
                OnUpdateDiagnostics,
                m_securityDiagnostics,
                OnUpdateSecurityDiagnostics);

            // report the audit event.
            ReportAuditCreateSessionEvent(systemContext);

            TraceState("CREATED");
        }
Beispiel #32
0
        public async Task <IndividualUserIdentityResponse> UpdateUserIdentityAsync(long userId, UserIdentity identity)
        {
            var body = new { identity };

            return(await GenericPostAsync <IndividualUserIdentityResponse>($"users/{userId}/identities.json", body));
        }
Beispiel #33
0
        /// <summary>
        /// Activates an existing session
        /// </summary>
        public virtual bool ActivateSession(
            OperationContext context,
            NodeId authenticationToken,
            SignatureData clientSignature,
            List <SoftwareCertificate> clientSoftwareCertificates,
            ExtensionObject userIdentityToken,
            SignatureData userTokenSignature,
            StringCollection localeIds,
            out byte[]                      serverNonce)
        {
            serverNonce = null;

            Session           session         = null;
            UserIdentityToken newIdentity     = null;
            UserTokenPolicy   userTokenPolicy = null;

            lock (m_lock)
            {
                // find session.
                if (!m_sessions.TryGetValue(authenticationToken, out session))
                {
                    throw new ServiceResultException(StatusCodes.BadSessionClosed);
                }

                // create new server nonce.
                serverNonce = new byte[m_minNonceLength];
                IBuffer buffer = CryptographicBuffer.GenerateRandom((uint)m_minNonceLength);
                CryptographicBuffer.CopyToByteArray(buffer, out serverNonce);

                // validate before activation.
                session.ValidateBeforeActivate(
                    context,
                    clientSignature,
                    clientSoftwareCertificates,
                    userIdentityToken,
                    userTokenSignature,
                    localeIds,
                    serverNonce,
                    out newIdentity,
                    out userTokenPolicy);
            }

            IUserIdentity identity          = null;
            IUserIdentity effectiveIdentity = null;
            ServiceResult error             = null;

            try
            {
                // check if the application has a callback which validates the identity tokens.
                lock (m_eventLock)
                {
                    if (m_ImpersonateUser != null)
                    {
                        ImpersonateEventArgs args = new ImpersonateEventArgs(newIdentity, userTokenPolicy);
                        m_ImpersonateUser(session, args);

                        if (ServiceResult.IsBad(args.IdentityValidationError))
                        {
                            error = args.IdentityValidationError;
                        }
                        else
                        {
                            identity          = args.Identity;
                            effectiveIdentity = args.EffectiveIdentity;
                        }
                    }
                }

                // parse the token manually if the identity is not provided.
                if (identity == null)
                {
                    identity = new UserIdentity(newIdentity);
                }

                // use the identity as the effectiveIdentity if not provided.
                if (effectiveIdentity == null)
                {
                    effectiveIdentity = identity;
                }
            }
            catch (Exception e)
            {
                if (e is ServiceResultException)
                {
                    throw;
                }

                throw ServiceResultException.Create(
                          StatusCodes.BadIdentityTokenInvalid,
                          e,
                          "Could not validate user identity token: {0}",
                          newIdentity);
            }

            // check for validation error.
            if (ServiceResult.IsBad(error))
            {
                throw new ServiceResultException(error);
            }

            // activate session.
            bool contextChanged = session.Activate(
                context,
                clientSoftwareCertificates,
                newIdentity,
                identity,
                effectiveIdentity,
                localeIds,
                serverNonce);

            // raise session related event.
            if (contextChanged)
            {
                RaiseSessionEvent(session, SessionEventReason.Activated);
            }

            // indicates that the identity context for the session has changed.
            return(contextChanged);
        }
 public Task <IdentityResult> CreateUserAsync(UserIdentity user)
 {
     return(_userManager.CreateAsync(user));
 }
 private SecurityPrincipal(Dictionary<string,bool> securityPermissions, Dictionary<int,string> securityGroups, string username)
 {
     this._securityPermissions = securityPermissions;
     this._securityGroups = securityGroups;
     this._identity = UserIdentity.CreateUserIdentity(username);
 }
Beispiel #36
0
 public Task <IPhilatelicCollection> GetCollectionAsync(UserIdentity collector, Guid id)
 {
     // collector not needed here - given how data are organised in memeory
     return(Task.Run(() => InMemoryStore.PhilatelicCollections[id]));
 }
Beispiel #37
0
 public Task <IEnumerable <ICollectableCollection> > GetCollectionNamesAsync(UserIdentity collectorId)
 {
     return(Task.Run(() => InMemoryStore.CollectorColletions[collectorId.Id]
                     .Select(id => InMemoryStore.PhilatelicCollections[id]) as IEnumerable <ICollectableCollection>));
 }
Beispiel #38
0
        public IndividualUserIdentityResponse UpdateUserIdentity(long userId, UserIdentity identity)
        {
            var body = new { identity };

            return(GenericPost <IndividualUserIdentityResponse>(string.Format("users/{0}/identities.json", userId), body));
        }
Beispiel #39
0
 public static UserIdentity MapTo(this UserIdentity user, UserIdentity newUser)
 {
     return(Mapper.Map(newUser, user));
 }
        public UserIdentity GetIdentity(int customerID)
        {
            dynamic identity = null;

            using (var context = ExigoDAL.Sql())
            {
                try
                {
                    identity = context.Query <UserIdentity>(@"
                        SELECT  
                            c.CustomerID
                            , c.FirstName
                            , c.LastName
                            , c.Company
                            , c.LoginName                       
                            , c.CustomerTypeID
                            , c.CustomerStatusID
                            , c.LanguageID
                            , c.DefaultWarehouseID
                            , c.CurrencyCode
                            , c.MainCountry AS 'Country'

                        FROM Customers c

                        WHERE c.CustomerID = @customerid
                        AND c.CanLogin = 1 -- Ensure that the Customer is allowed to Log in
                    ", new
                    {
                        customerid = customerID
                    }).FirstOrDefault();

                    // Use the web service as a backup
                    if (identity == null)
                    {
                        var customer = ExigoDAL.WebService().GetCustomers(new GetCustomersRequest()
                        {
                            CustomerID = customerID
                        }).Customers.FirstOrDefault();

                        if (customer != null)
                        {
                            identity = new UserIdentity()
                            {
                                CustomerID         = customer.CustomerID,
                                FirstName          = customer.FirstName,
                                LastName           = customer.LastName,
                                Company            = customer.Company,
                                LoginName          = customer.LoginName,
                                CustomerTypeID     = customer.CustomerType,
                                CustomerStatusID   = customer.CustomerStatus,
                                LanguageID         = customer.LanguageID,
                                DefaultWarehouseID = customer.DefaultWarehouseID = (customer.DefaultWarehouseID > 0) ? customer.DefaultWarehouseID : Warehouses.Default,
                                CurrencyCode       = customer.CurrencyCode,
                                Country            = customer.MainCountry
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error Getting Identity: {Message}", ex.Message);
                    return(null);
                }
            }

            return(identity);
        }
 public Task <UserIdentity> GetUserAsync(UserIdentity user)
 {
     return(_userManager.FindByIdAsync(user.Id.ToString()));
 }
Beispiel #42
0
        public IndividualUserIdentityResponse UpdateUserIdentity(long userId, UserIdentity identity)
        {
            var body = new { identity };

            return(GenericPost <IndividualUserIdentityResponse>($"users/{userId}/identities.json", body));
        }
 public UserPrincipal(UserIdentity identity) : base(identity, identity.Roles)
 {
 }
Beispiel #44
0
 internal static void RegisterReactionWait(TaskCompletionSource <string> completionSource, string[] option, ulong messageId, UserIdentity userId)
 {
     ReactionWaits.Add(new ReactionWait(completionSource, option, messageId, userId));
 }
Beispiel #45
0
            public void Setup()
            {
                Logger = new Mock <ILogger>();
                PaperPusherClientMock = new Mock <IPaperpusherClient>();
                CostBuilderMock       = new Mock <ICostBuilder>();
                PgUserServiceMock     = new Mock <IPgUserService>();
                EventService          = new Mock <IEventService>();
                PermissionService     = new Mock <IPermissionService>();
                SearchServiceMock     = new Mock <IElasticSearchService>();
                ActionBuilderMock     = new Mock <IActionBuilder>();
                ModuleService         = new Mock <IModuleService>();
                ActionBuilders        = new[]
                {
                    new Lazy <IActionBuilder, PluginMetadata>(
                        () => ActionBuilderMock.Object, new PluginMetadata {
                        BuType = BuType.Pg
                    })
                };
                UserServices = new EditableList <Lazy <IPgUserService, PluginMetadata> >
                {
                    new Lazy <IPgUserService, PluginMetadata>(
                        () => PgUserServiceMock.Object, new PluginMetadata {
                        BuType = BuType.Pg
                    })
                };
                var costApprovalServiceMock = new Mock <ICostApprovalService>();

                Mapper = new Mock <IMapper>();
                ActivityLogServiceMock = new Mock <IActivityLogService>();

                CostBuilders = new EditableList <Lazy <ICostBuilder, PluginMetadata> >
                {
                    new Lazy <ICostBuilder, PluginMetadata>(
                        () => CostBuilderMock.Object, new PluginMetadata {
                        BuType = BuType.Pg
                    })
                };
                PostProcessorMock = new Mock <IActionPostProcessor>();
                PostProcessors    = new EditableList <Lazy <IActionPostProcessor, PluginMetadata> >
                {
                    new Lazy <IActionPostProcessor, PluginMetadata>(
                        () => PostProcessorMock.Object, new PluginMetadata {
                        BuType = BuType.Pg
                    })
                };

                User = new UserIdentity
                {
                    Email    = "UserName",
                    AgencyId = Guid.NewGuid(),
                    BuType   = BuType.Pg,
                    Id       = Guid.NewGuid()
                };
                CostStageRevisionPermissionServiceMock = new Mock <ICostStageRevisionPermissionService>();
                SupportNotificationServiceMock         = new Mock <ISupportNotificationService>();
                EFContext = EFContextFactory.CreateInMemoryEFContext();

                CostService = new CostService(
                    CostBuilders,
                    UserServices,
                    EventService.Object,
                    PermissionService.Object,
                    PaperPusherClientMock.Object,
                    Logger.Object,
                    SearchServiceMock.Object,
                    EFContext,
                    ActionBuilders,
                    costApprovalServiceMock.Object,
                    Mapper.Object,
                    ActivityLogServiceMock.Object,
                    PostProcessors,
                    CostStageRevisionPermissionServiceMock.Object,
                    SupportNotificationServiceMock.Object,
                    ModuleService.Object
                    );
            }
Beispiel #46
0
        /// <summary>
        /// Erstellt eine Session mit den Informationen des Konstruktors.
        /// Es ist nur eine Session pro Server zulässig.
        /// </summary>
        /// <returns></returns>
        private async Task CreateSessionAsync()
        {
            if (m_Session == null)
            {
                // Die Konfiguration für die Client/Server Beziehung wird erstellt.
                m_Config = new ApplicationConfiguration()
                {
                    ApplicationName = "UARC-Collector",
                    ApplicationType = ApplicationType.Client,

                    // ApplicationUri definiert den Namespace (Gültigkeitsbereich) des Zertifikats.
                    // Dieser Syntax muss für eine hohe Kompatibilität beibehalten werden.
                    ApplicationUri = "urn:" + Utils.GetHostName(),

                    SecurityConfiguration = new SecurityConfiguration
                    {
                        ApplicationCertificate = new CertificateIdentifier
                        {
                            StoreType   = CertificateStoreType.X509Store,
                            StorePath   = "CurrentUser\\My",
                            SubjectName = "UARC-Collector"
                        },

                        TrustedPeerCertificates = new CertificateTrustList
                        {
                            StoreType = "Directory",
                            StorePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "OPC Foundation/CertificateStores/UA Applications"),
                        },
                        TrustedIssuerCertificates = new CertificateTrustList
                        {
                            StoreType = "Directory",
                            StorePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "OPC Foundation/CertificateStores/UA Certificate Authorities"),
                        },
                        RejectedCertificateStore = new CertificateTrustList
                        {
                            StoreType = "Directory",
                            StorePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "OPC Foundation/CertificateStores/RejectedCertificates"),
                        },
                        NonceLength = 32,

                        AutoAcceptUntrustedCertificates = autoAccept
                    },
                    TransportConfigurations = new TransportConfigurationCollection(),
                    TransportQuotas         = new TransportQuotas {
                        OperationTimeout = 15000
                    },
                    ClientConfiguration = new ClientConfiguration {
                        DefaultSessionTimeout = TimeOut
                    }
                };

                // Die Konfiguration wird überprüft.
                await m_Config.Validate(ApplicationType.Client);

                // Wenn kein Zertifikat vorhanden ist, ist das Bool "haveAppCertificate" false.
                bool haveAppCertificate = m_Config.SecurityConfiguration.ApplicationCertificate.Certificate != null;

                // Wenn kein Zertifikat vorhanden ist, wird eine selbstsigniertes Zertifikat erzeugt.
                if (!haveAppCertificate)
                {
                    #region Varibalen zur Zertifikats erstellung
                    string           storeType        = m_Config.SecurityConfiguration.ApplicationCertificate.StoreType;
                    string           storePath        = m_Config.SecurityConfiguration.ApplicationCertificate.StorePath;
                    string           password         = null;
                    string           applicationUri   = m_Config.ApplicationUri;
                    string           applicationName  = m_Config.ApplicationName;
                    string           subjectName      = m_Config.SecurityConfiguration.ApplicationCertificate.SubjectName;
                    IList <String>   domainNames      = null;                               //GetLocalIpAddressAndDns(), von UAClient Helper API
                    ushort           keySize          = CertificateFactory.defaultKeySize;  //must be multiples of 1024 (Beispiel 2048),
                    DateTime         startTime        = System.DateTime.Now;
                    ushort           lifetimeInMonths = CertificateFactory.defaultLifeTime; //in month (Beispiel 24)
                    ushort           hashSizeInBits   = CertificateFactory.defaultHashSize; //(Beispiel 128)
                    bool             isCA             = false;
                    X509Certificate2 issuerCAKeyCert  = null;
                    byte[]           publicKey        = null;
                    #endregion

                    X509Certificate2 certificate = CertificateFactory.CreateCertificate
                                                   (
                        storeType,
                        storePath,
                        password,
                        applicationUri,
                        applicationName,
                        subjectName,
                        domainNames,
                        keySize,
                        startTime,
                        lifetimeInMonths,
                        hashSizeInBits,
                        isCA,
                        issuerCAKeyCert,
                        publicKey
                                                   );

                    certificate.Verify();

                    m_Config.SecurityConfiguration.ApplicationCertificate.Certificate = certificate;
                }

                // "haveAppCertificate"  wird neu beschrieben.
                haveAppCertificate = (m_Config.SecurityConfiguration.ApplicationCertificate.Certificate != null);

                if (haveAppCertificate)
                {
                    //m_config.ApplicationUri = Utils.GetApplicationUriFromCertificate(m_config.SecurityConfiguration.ApplicationCertificate.Certificate);

                    if (m_Config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                    {
                        m_Config.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation;
                    }
                }

                // Der passende Enpoint wird ausgewählt.
                var selectedEndpoint = CoreClientUtils.SelectEndpoint(EndpointUrl, haveAppCertificate, 15000);
                // EndpointConfiguration wiird erstellt.
                var endpointConfiguration = EndpointConfiguration.Create(m_Config);
                // Enpoint für Client wird erstellt.
                var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);

                // UserIdentity wird erstellt.
                UserIdentity userIdentity = null;

                if ((Username != null && Username != "") && (Password != null && Password != ""))
                {
                    userIdentity = new UserIdentity(Username, Password);
                }
                else
                {
                    userIdentity = new UserIdentity(); // --> AnonymousIdentityToken
                }
                // Session wird erstellt.
                try
                {
                    m_Session = await Session.Create(m_Config, endpoint, true, true, "Session_" + ServerLabel, 60000, userIdentity, null);
                }
                catch (Exception e)
                {
                    if (e.Message == null)
                    {
                        e = new Exception(String.Format("Session {0} konnte nicht erfolgreich erstellt werden.", ServerLabel));
                        throw e;
                    }
                    else
                    {
                        throw e;
                    }
                }

                // KeepAliveHandler wird hinzugefügt.
                m_Session.KeepAlive += Client_KeepAlive;

                // Default Subscription null setzen, um Fehler zu verhindern
                m_Session.DefaultSubscription = null;
            }
            else
            {
                throw new Exception("Eine Session ist bereits vorhanden");
            }
        }
Beispiel #47
0
        /// <summary>
        /// Connects to the OPC server asynchronously.
        /// </summary>
        public async Task <bool> ConnectAsync(OpcConnectionOptions connectionOptions, int operationTimeout = -1)
        {
            ApplicationInstance application = new ApplicationInstance
            {
                ApplicationName   = string.Format("DrvOpcUa_{0} Driver", deviceNumStr),
                ApplicationType   = ApplicationType.Client,
                ConfigSectionName = "Scada.Comm.Drivers.DrvOpcUa"
            };

            // load the application configuration
            // TODO: use stream instead of file after updating OPCFoundation.NetStandard.Opc.Ua
            WriteConfigFile(out string configFileName);
            ApplicationConfiguration config = await application.LoadApplicationConfiguration(configFileName, false);

            // check the application certificate
            bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0);

            if (!haveAppCertificate)
            {
                throw new ScadaException(Locale.IsRussian ?
                                         "Сертификат экземпляра приложения недействителен!" :
                                         "Application instance certificate invalid!");
            }

            if (haveAppCertificate)
            {
                config.ApplicationUri = X509Utils.GetApplicationUriFromCertificate(
                    config.SecurityConfiguration.ApplicationCertificate.Certificate);

                if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    AutoAccept = true;
                }

                config.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation;
            }
            else
            {
                log.WriteLine(Locale.IsRussian ?
                              "Предупреждение: отсутствует сертификат приложения, используется незащищенное соединение." :
                              "Warning: missing application certificate, using unsecure connection.");
            }

            // create session
            EndpointDescription selectedEndpoint = operationTimeout > 0
                ? CoreClientUtils.SelectEndpoint(connectionOptions.ServerUrl, haveAppCertificate, operationTimeout)
                : CoreClientUtils.SelectEndpoint(connectionOptions.ServerUrl, haveAppCertificate);

            selectedEndpoint.SecurityMode      = connectionOptions.SecurityMode;
            selectedEndpoint.SecurityPolicyUri = connectionOptions.GetSecurityPolicy();
            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(config);
            ConfiguredEndpoint    endpoint     = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
            UserIdentity          userIdentity = connectionOptions.AuthenticationMode == AuthenticationMode.Username ?
                                                 new UserIdentity(connectionOptions.Username, connectionOptions.Password) :
                                                 new UserIdentity(new AnonymousIdentityToken());

            OpcSession = await Session.Create(config, endpoint, false,
                                              "Rapid SCADA DrvOpcUa_" + deviceNumStr,
                                              (uint)config.ClientConfiguration.DefaultSessionTimeout, userIdentity, null);

            log.WriteLine(Locale.IsRussian ?
                          "OPC сессия успешно создана: {0}" :
                          "OPC session created successfully: {0}", connectionOptions.ServerUrl);
            return(true);
        }
Beispiel #48
0
        //public LockStatus GetLockStatus(ObjectKey objectKey, out UserIdentity owner)
        //{
        //    return _lockingStorage.GetLockStatus(objectKey, out owner);
        //}

        public bool ReleaseLock(UserIdentity user, ObjectKey objectKey)
        {
            return _lockingStorage.ReleaseLock(user, objectKey);
        }
Beispiel #49
0
 private void SetupUserIdentity()
 {
     userIdentity = new UserIdentity("GRS", 1, 1, "john.doe", "corporate.net", "ONEDEV", DateTime.Now, true, "", false, null, null, null);
     userManager.Setup(p => p.UserIdentity).Returns(userIdentity);
 }
Beispiel #50
0
 public void UpdateUser(UserIdentity userIdentity)
 {
     throw new NotImplementedException();
 }
Beispiel #51
0
        /// <summary>
        ///     Configure <see cref="KubeClientOptions"/> from the settings specified in the <see cref="K8sConfig"/>.
        /// </summary>
        /// <param name="kubeClientOptions">
        ///
        /// </param>
        /// <param name="kubeContextName">
        ///     The name of the Kubernetes context to use.
        ///
        ///     If not specified, then the current context (as configured) will be used.
        /// </param>
        /// <param name="defaultKubeNamespace">
        ///     The default Kubernetes namespace to use.
        /// </param>
        /// <returns>
        ///     The configured <see cref="KubeClientOptions"/>.
        /// </returns>
        public KubeClientOptions ConfigureKubeClientOptions(KubeClientOptions kubeClientOptions, string kubeContextName = null, string defaultKubeNamespace = null)
        {
            if (kubeClientOptions == null)
            {
                throw new ArgumentNullException(nameof(kubeClientOptions));
            }

            string targetContextName = kubeContextName ?? CurrentContextName;

            if (String.IsNullOrWhiteSpace(targetContextName))
            {
                throw new InvalidOperationException("The kubeContextName parameter was not specified, and the Kubernetes client configuration does not specify a current context.");
            }

            Context targetContext = Contexts.Find(context => context.Name == targetContextName);

            if (targetContext == null)
            {
                throw new InvalidOperationException($"Cannot find a context in the Kubernetes client configuration named '{targetContextName}'.");
            }

            Cluster targetCluster = Clusters.Find(cluster => cluster.Name == targetContext.Config.ClusterName);

            if (targetCluster == null)
            {
                throw new InvalidOperationException($"Cannot find a cluster in the Kubernetes client configuration named '{targetContext.Config.ClusterName}'.");
            }

            UserIdentity targetUser = UserIdentities.Find(user => user.Name == targetContext.Config.UserName);

            if (targetUser == null)
            {
                throw new InvalidOperationException($"Cannot find a user identity in the Kubernetes client configuration named '{targetContext.Config.UserName}'.");
            }

            kubeClientOptions.ApiEndPoint       = new Uri(targetCluster.Config.Server);
            kubeClientOptions.KubeNamespace     = defaultKubeNamespace;
            kubeClientOptions.ClientCertificate = targetUser.Config.GetClientCertificate();
            kubeClientOptions.AllowInsecure     = targetCluster.Config.AllowInsecure;
            kubeClientOptions.CertificationAuthorityCertificate = targetCluster.Config.GetCACertificate();

            // Mixed authentication types are not supported.
            if (kubeClientOptions.ClientCertificate == null)
            {
                string accessToken = targetUser.Config.GetRawToken();
                if (!String.IsNullOrWhiteSpace(accessToken))
                {
                    kubeClientOptions.AccessToken  = accessToken;
                    kubeClientOptions.AuthStrategy = KubeAuthStrategy.BearerToken;
                }
                else
                {
                    kubeClientOptions.AuthStrategy = KubeAuthStrategy.None;
                }

                AuthProviderConfig authProvider = targetUser.Config.AuthProvider;
                if (authProvider != null)
                {
                    kubeClientOptions.AuthStrategy = KubeAuthStrategy.BearerTokenProvider;

                    if (authProvider.Config.TryGetValue("cmd-path", out object accessTokenCommand))
                    {
                        kubeClientOptions.AccessTokenCommand = (string)accessTokenCommand;
                    }

                    if (authProvider.Config.TryGetValue("cmd-args", out object accessTokenCommandArguments))
                    {
                        kubeClientOptions.AccessTokenCommandArguments = (string)accessTokenCommandArguments;
                    }

                    if (authProvider.Config.TryGetValue("token-key", out object accessTokenSelector))
                    {
                        kubeClientOptions.AccessTokenSelector = (string)accessTokenSelector;
                    }

                    if (authProvider.Config.TryGetValue("expiry-key", out object accessTokenExpirySelector))
                    {
                        kubeClientOptions.AccessTokenExpirySelector = (string)accessTokenExpirySelector;
                    }

                    if (authProvider.Config.TryGetValue("access-token", out object initialAccessToken))
                    {
                        kubeClientOptions.InitialAccessToken = (string)initialAccessToken;
                    }

                    if (authProvider.Config.TryGetValue("expiry", out object initialTokenExpiry))
                    {
                        kubeClientOptions.InitialTokenExpiryUtc = DateTime.Parse((string)initialTokenExpiry,
                                                                                 provider: CultureInfo.InvariantCulture,
                                                                                 styles: DateTimeStyles.AssumeUniversal
                                                                                 );
                    }
                }
            }
            else
            {
                kubeClientOptions.AuthStrategy = KubeAuthStrategy.ClientCertificate;
            }

            return(kubeClientOptions);
        }
 private string GetSessionKey(UserIdentity userIdentity) => $"user-{userIdentity.UserId}";
 protected override FilesGroup InitDownload(UserIdentity userIdentity, FilesGroup resource)
 {
     return _presentationTransfer.InitPresentationExport(userIdentity, resource);
 }
Beispiel #54
0
        private async Task <UserIdentity> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var user = new UserIdentity
            {
                UserName = Guid.NewGuid().ToString(),
            };
            var identityResult = await _userManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            if (filtered.Any())
            {
                identityResult = await _userManager.AddClaimsAsync(user, filtered);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }
            }

            identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            return(user);
        }
Beispiel #55
0
        //public IPresentationDAL PresentationDAL{get; set;}

        #region ILockService Members

        public bool AcquireLock(ICommunicationObject communicationObject, UserIdentity user, ObjectKey objectKey, RequireLock requireLock)
        {
            return _lockingStorage.AcquireLock(communicationObject, user, objectKey, requireLock);
        }
        public async Task <IActionResult> ExternalLoginCallback()
        {
            // read external identity from the temporary cookie
            var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

            if (result?.Succeeded != true)
            {
                throw new Exception("External authentication error");
            }

            // lookup our user and external provider info
            var(user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);

            if (user == null)
            {
                // this might be where you might initiate a custom workflow for user registration
                // in this sample we don't show how that would be done, as our sample implementation
                // simply auto-provisions new external user
                user = await AutoProvisionUserAsync(provider, providerUserId, claims);

                if (user == null)
                {
                    return(RedirectToAction("LoginError", "Home", new { Error = string.Join(" ", _notifications.GetNotifications().Select(a => $"{a.Key}: {a.Value}")) }));
                }
            }

            // this allows us to collect any additonal claims or properties
            // for the specific prtotocols used and store them in the local auth cookie.
            // this is typically used to store data needed for signout from those protocols.
            var additionalLocalClaims = new List <Claim>();
            var localSignInProps      = new AuthenticationProperties();

            ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);

            // issue authentication cookie for user
            // we must issue the cookie maually, and can't use the SignInManager because
            // it doesn't expose an API to issue additional claims from the login workflow
            // I don't have pride of this.
            var s = new UserIdentity()
            {
                Id                   = user.Id,
                Name                 = user.Name,
                SecurityStamp        = user.SecurityStamp,
                AccessFailedCount    = user.AccessFailedCount,
                Bio                  = user.Bio,
                Company              = user.Company,
                Email                = user.Email,
                EmailConfirmed       = user.EmailConfirmed,
                JobTitle             = user.JobTitle,
                LockoutEnabled       = user.LockoutEnabled,
                LockoutEnd           = user.LockoutEnd,
                PhoneNumber          = user.PhoneNumber,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                Picture              = user.Picture,
                TwoFactorEnabled     = user.TwoFactorEnabled,
                Url                  = user.Url,
                UserName             = user.UserName,
            };
            var principal = await _signInManager.CreateUserPrincipalAsync(s);

            additionalLocalClaims.AddRange(principal.Claims);
            var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id.ToString();
            await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id.ToString(), name));

            await HttpContext.SignInAsync(user.Id.ToString(), name, provider, localSignInProps, additionalLocalClaims.ToArray());

            // delete temporary cookie used during external authentication
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            // validate return URL and redirect back to authorization endpoint or a local page
            var returnUrl = result.Properties.Items["returnUrl"];

            // check if external login is in the context of an OIDC request
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context != null)
            {
                if (await _clientStore.IsPkceClientAsync(context.ClientId))
                {
                    // if the client is PKCE then we assume it's native, so this change in how to
                    // return the response is for better UX for the end user.
                    return(View("Redirect", new RedirectViewModel {
                        RedirectUrl = returnUrl
                    }));
                }
            }

            return(Redirect(returnUrl));
        }
Beispiel #57
0
        public async Task <IndividualUserIdentityResponse> AddUserIdentityAsync(long userId, UserIdentity identity)
        {
            var body = new { identity };

            return(await GenericPostAsync <IndividualUserIdentityResponse>(string.Format("users/{0}/identities.json", userId), body));
        }
        public async Task <IdentityResult> DeleteUserAsync(UserIdentity user)
        {
            var userIdentity = await _userManager.FindByIdAsync(user.Id.ToString());

            return(await _userManager.DeleteAsync(userIdentity));
        }
Beispiel #59
0
 public static UserDto ToModel(this UserIdentity user)
 {
     return(Mapper.Map <UserDto>(user));
 }
        /// <summary>
        ///     Add <see cref="KubeClientOptions"/> from local Kubernetes client configuration.
        /// </summary>
        /// <param name="services">
        ///     The service collection to configure.
        /// </param>
        /// <param name="kubeConfigFileName">
        ///     The optional name of a specific configuration file to use (defaults to "$HOME/.kube/config").
        /// </param>
        /// <param name="kubeContextName">
        ///     The optional name of a specific Kubernetes client context to use.
        /// </param>
        /// <param name="defaultKubeNamespace">
        ///     The default namespace to use (if not specified, "default" is used).
        /// </param>
        /// <returns>
        ///     The configured service collection.
        /// </returns>
        public static IServiceCollection AddKubeClientOptionsFromKubeConfig(this IServiceCollection services, string kubeConfigFileName = null, string kubeContextName = null, string defaultKubeNamespace = "default")
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (String.IsNullOrWhiteSpace(defaultKubeNamespace))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'defaultNamespace'.", nameof(defaultKubeNamespace));
            }

            if (String.IsNullOrWhiteSpace(kubeConfigFileName))
            {
                kubeConfigFileName = Path.GetFullPath(Path.Combine(
                                                          Environment.GetEnvironmentVariable("HOME"),
                                                          ".kube",
                                                          "config"
                                                          ));
            }
            FileInfo kubeConfigFile = new FileInfo(kubeConfigFileName);

            // IOptions<KubeClientOptions>
            services.Configure <KubeClientOptions>(kubeClientOptions =>
            {
                Config config = Config.Load(kubeConfigFile);

                string targetContextName = kubeContextName ?? config.CurrentContextName;
                if (String.IsNullOrWhiteSpace(targetContextName))
                {
                    throw new InvalidOperationException("The kubeContextName parameter was not specified, and the Kubernetes client configuration does not specify a current context.");
                }

                Context targetContext = config.Contexts.Find(context => context.Name == targetContextName);
                if (targetContext == null)
                {
                    throw new InvalidOperationException($"Cannot find a context in the Kubernetes client configuration named '{targetContextName}'.");
                }

                Cluster targetCluster = config.Clusters.Find(cluster => cluster.Name == targetContext.Config.ClusterName);
                if (targetCluster == null)
                {
                    throw new InvalidOperationException($"Cannot find a cluster in the Kubernetes client configuration named '{targetContext.Config.ClusterName}'.");
                }

                UserIdentity targetUser = config.UserIdentities.Find(user => user.Name == targetContext.Config.UserName);
                if (targetUser == null)
                {
                    throw new InvalidOperationException($"Cannot find a user identity in the Kubernetes client configuration named '{targetContext.Config.UserName}'.");
                }

                kubeClientOptions.ApiEndPoint   = new Uri(targetCluster.Config.Server);
                kubeClientOptions.KubeNamespace = defaultKubeNamespace;

                kubeClientOptions.ClientCertificate = targetUser.Config.GetClientCertificate();
                kubeClientOptions.CertificationAuthorityCertificate = targetCluster.Config.GetCACertificate();
                kubeClientOptions.AccessToken = targetUser.Config.GetRawToken();
            });

            return(services);
        }