Exemple #1
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(textBoxPrincipalRealm.Text))
            {
                MessageBox.Show(this,
                                Properties.Resources.CredentialsEditorForm_MustProvideARealm, Properties.Resources.MessageBox_ErrorString,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (String.IsNullOrWhiteSpace(textBoxUsername.Text))
            {
                MessageBox.Show(this,
                                Properties.Resources.CredentialsEditorForm_MustProvideAUsername, Properties.Resources.MessageBox_ErrorString,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                SecurityPrincipal p = new SecurityPrincipal(typeof(AuthenticationCredentials), textBoxPrincipalName.Text, textBoxPrincipalRealm.Text);
                if (_checkPrincipal(p) || (MessageBox.Show(this,
                                                           String.Format(Properties.Resources.CredentialsEditorForm_PrincipalAlreadyExists, textBoxPrincipalName.Text, textBoxPrincipalRealm.Text),
                                                           Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
                {
                    Principal = p;
                    Username  = textBoxUsername.Text;
                    Password  = textBoxPassword.Text;
                    Domain    = textBoxDomain.Text;

                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
        }
Exemple #2
0
            /// <summary>
            /// switches the current security principal to our custom security principal which works
            /// with the security information read from the database and passed along here
            /// </summary>
            /// <param name="SecurityGroups">the list of secuiryt groups the user belongs too</param>
            /// <param name="SecurityRights">the list of security rights the user has</param>
            /// <param name="UserInfo">list of information we have about the user itself</param>
            /// <returns>returns the current IPrincipal object so it can be restored after a log off of the user; returns null if we don't switch the security principal</returns>
            private static IPrincipal SetSecurityPrincipal(Hashtable SecurityGroups, Hashtable SecurityRights, Hashtable UserInfo)
            {
                // set that we want to use authentication within the current app-domain; this means
                // a thread will have a IPrincipal associated which is then used by the .NET
                // security classes when checking role based security
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                // we switch to the new security principal only if we didn't do so already; this
                // protects us from the consumer calling this method multiple times
                if (!(Thread.CurrentPrincipal is SecurityPrincipal))
                {
                    // create a new instance of the security principal which we can do only within
                    // a class memebr as we marked the constructor private
                    SecurityPrincipal TheSecurityPrincipal = SetSecurityValues(SecurityGroups, SecurityRights, UserInfo);

                    // get a reference to the current security principal so the caller can keep hold of it
                    IPrincipal CurrentSecurityPrincipal = Thread.CurrentPrincipal;

                    // set the security principal for the current thread to the newly created one
                    Thread.CurrentPrincipal = TheSecurityPrincipal;

                    // return the current security principal;
                    return(CurrentSecurityPrincipal);
                }

                // return null if we don't switch the security principal
                else
                {
                    return(null);
                }
            }
Exemple #3
0
        private void AddCredential(SecurityPrincipal principal, AuthenticationCredentials creds)
        {
            ListViewItem item = new ListViewItem(String.Format("{0}@{1}", principal.Name, principal.Realm));

            item.SubItems.Add(creds.Username);
            item.SubItems.Add(creds.Domain);
        }
Exemple #4
0
        public IHttpActionResult GetRecordCount(string modelName)
        {
            // Proxy all other requests
            SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal;

            if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator"))
            {
                return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized."));
            }

            object record;

            using (DataContext dataContext = new DataContext("systemSettings"))
            {
                try
                {
                    Type type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName);
                    record = dataContext.Table(type).QueryRecordCount();
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.ToString()));
                }
            }

            return(Ok(record));
        }
        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>A string array containing the names of all the roles stored in the data source for the configured applicationName.</returns>
        public override string[] GetAllRoles()
        {
            // Get all the groups in Active Directory.
            List <System.DirectoryServices.Protocols.SearchResultEntry> entries = ad.GetEntries("(objectCategory = group)");

            // Check that entries were returned.
            if (entries != null)
            {
                // There are entries in the list.

                // Create a list to hold the names of the roles found.
                List <string> roleNames = new List <string>();

                // Create groups from the entries.
                foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in entries)
                {
                    SecurityPrincipal securityPrincipal = new SecurityPrincipal(ad, entry);
                    roleNames.Add(securityPrincipal.SAMAccountName);
                }

                return(roleNames.ToArray());
            }
            else
            {
                // No entries were returned.
                return(new string[] { });
            }
        }
        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>A string array containing the names of all the roles stored in the data source for the configured applicationName.</returns>
        public override string[] GetAllRoles()
        {
            // Create a wildcard group name that corresponds to groups maintained by this application.
            string wildcardGroupName = GetGroupName("*");

            // Search Active Directory for groups corresponding to roles managed by this application.
            List <System.DirectoryServices.Protocols.SearchResultEntry> entries = ad.GetEntriesBySAMAccountName(wildcardGroupName);

            // Check that entries were returned.
            if (entries != null)
            {
                // There are entries in the list.

                // Create a list to hold the names of the roles found.
                List <String> roleNames = new List <String>();

                // Create groups from the entries.
                foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in entries)
                {
                    SecurityPrincipal securityPrincipal = new SecurityPrincipal(ad, entry);
                    if (securityPrincipal.IsGroup)
                    {
                        // Get the name of the role from the group name.
                        roleNames.Add(GetRoleName(securityPrincipal.SAMAccountName));
                    }
                }

                return(roleNames.ToArray());
            }
            else
            {
                // No entries were returned.
                return(new string[] { });
            }
        }
Exemple #7
0
        private void ShowSecurityDialog(DisplayType displayType, string errorMessage = null)
        {
            SecurityPortal    securityDialog   = new SecurityPortal(displayType);
            ISecurityProvider securityProvider = SecurityPrincipal.Identity.Provider;

            // Show authentication failure reason if one was defined and user didn't force another message
            if ((object)errorMessage == null && (object)securityProvider != null)
            {
                errorMessage = securityProvider.AuthenticationFailureReason;
            }

            if (!string.IsNullOrWhiteSpace(errorMessage))
            {
                securityDialog.ProviderFailure = true;
                securityDialog.DisplayErrorMessage(errorMessage);
            }

            // Show the WPF security dialog
            if (!securityDialog.ShowDialog().GetValueOrDefault())
            {
                // User chose to cancel security action. If the secure window has no parent,
                // this is root window so exit application, otherwise just close the window
                if ((object)this.Owner == null)
                {
                    m_shutdownRequested = true;
                    Application.Current.Shutdown();
                }
                else
                {
                    this.Close();
                }
            }

            SecurityPrincipal = securityDialog.SecurityPrincipal;
        }
Exemple #8
0
        /// <summary>
        /// Called once by common code after initialization. If an authentication middle-ware
        /// responds directly to specifically known paths it must override this virtual,
        /// compare the request path to it's known paths, provide any response information
        /// as appropriate, and true to stop further processing.
        /// </summary>
        /// <returns>
        /// Returning false will cause the common code to call the next middle-ware in line.
        /// Returning true will cause the common code to begin the async completion journey
        /// without calling the rest of the middle-ware pipeline.
        /// </returns>
        public override Task <bool> InvokeAsync()
        {
            // Use Cases:
            //
            //  (1) Access resource marked as anonymous - let pipeline continue
            //  (2) Access resource as authenticated user - let pipeline continue
            //  --- remaining use cases are unauthorized ---
            //  (3) Access AuthTest with Basic scheme or unsupported browser - respond with 403 and abort pipeline
            //  (4) Access resource marked for auth failure redirection - respond with 302 and abort pipeline
            //  (5) Access all other resources - respond with 401 and abort pipeline
            //
            //  Unauthorized response logic:
            //      if use case == 3, respond with 403 (prevents browser prompt for credentials)
            //      else if use case == 4, respond with 302 (go back home)
            //      else respond with 401
            return(Task.Run(() =>
            {
                SecurityPrincipal securityPrincipal = Request.User as SecurityPrincipal;
                string urlPath = Request.Path.Value;

                // If request is for an anonymous resource or user is properly authenticated, allow
                // request to propagate through the Owin pipeline
                if (Options.IsAnonymousResource(urlPath) || securityPrincipal?.Identity.IsAuthenticated == true)
                {
                    return false; // Let pipeline continue
                }
                // Abort pipeline with appropriate response
                if (Options.IsAuthFailureRedirectResource(urlPath))
                {
                    string urlQueryString = Request.QueryString.HasValue ? "?" + Request.QueryString.Value : "";
                    byte[] pathBytes = Encoding.UTF8.GetBytes(urlPath + urlQueryString);
                    string base64Path = Convert.ToBase64String(pathBytes);
                    string encodedPath = WebUtility.UrlEncode(base64Path);
                    Response.Redirect($"{Options.LoginPage}?redir={encodedPath}");
                }
                else
                {
                    Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                }

                // Add current identity to unauthorized response header
                string currentIdentity = securityPrincipal?.Identity.Name ?? "anonymous";
                object value;

                if (Request.Environment.TryGetValue("OriginalPrincipal", out value))
                {
                    IPrincipal originalPrincpal = value as IPrincipal;

                    if ((object)originalPrincpal != null && (object)originalPrincpal.Identity != null)
                    {
                        currentIdentity = AdjustedUserName(originalPrincpal.Identity.Name);
                    }
                }

                Response.Headers.Add("CurrentIdentity", new[] { currentIdentity });
                Response.ReasonPhrase = SecurityPrincipal.GetFailureReasonPhrase(securityPrincipal, AuthorizationHeader?.Scheme, AssemblyInfo.EntryAssembly.Debuggable);

                return true; // Abort pipeline
            }));
        }
        public bool CheckUserInGroup(string group)
        {
            string       serverName = ConfigurationManager.AppSettings["ADServer"];
            string       userName   = ConfigurationManager.AppSettings["ADUserName"];
            string       password   = ConfigurationManager.AppSettings["ADPassword"];
            bool         result     = false;
            SecureString securePwd  = null;

            if (password != null)
            {
                securePwd = new SecureString();
                foreach (char chr in password.ToCharArray())
                {
                    securePwd.AppendChar(chr);
                }
            }
            try
            {
                ActiveDirectory   adConnectGroup = new ActiveDirectory(serverName, userName, securePwd);
                SearchResultEntry groupResult    = adConnectGroup.GetEntryByCommonName(group);
                Group             grp            = new Group(adConnectGroup, groupResult);
                SecurityPrincipal userPrincipal  = grp.Members.Find(sp => sp.SAMAccountName.ToLower() == System.Web.HttpContext.Current.User.Identity.Name.ToLower());
                if (userPrincipal != null)
                {
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            return(result);
        }
Exemple #10
0
        private void TxtUsernameKeyDown(object sender, KeyEventArgs e)
        {
            // if this is a debugging session login automattically
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // this has to be removed after development
                if (e.Control && e.Alt)
                {
                    if (txtUsername.Text == "")
                    {
                        txtUsername.Text = "su";
                    }
                    UserInformation userInfo = null;

                    if (BLL.Settings.UseNewUserManagement)
                    {
                        userInfo = Auth.Authenticate(txtUsername.Text);
                        if (userInfo == null)
                        {
                            //errorLogger.SaveError(0, 1, 1, 2, "Login Attempt", "Warehouse", new InvalidCredentialException("Invalid credentials, Username = " + username));
                            //return false;
                        }
                        Thread.CurrentPrincipal = SecurityPrincipal.CreateSecurityPrincipal(userInfo);
                    }

                    User usr = new User();
                    usr.Where.UserName.Value = txtUsername.Text;
                    usr.Query.Load();
                    LogUserIn(usr);
                }
            }
        }
Exemple #11
0
        private void editCredentialToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewCredentials.SelectedItems.Count > 0)
            {
                KeyValuePair <SecurityPrincipal, ICredentialObject> pair = (KeyValuePair <SecurityPrincipal, ICredentialObject>)listViewCredentials.SelectedItems[0].Tag;
                using (CredentialEditorForm frm = new CredentialEditorForm((p) => !p.Equals(pair.Key) && CheckPrincipal(p)))
                {
                    frm.Principal = pair.Key;
                    AuthenticationCredentials c = pair.Value as AuthenticationCredentials;
                    frm.Username = c.Username;
                    frm.Password = c.Password;
                    frm.Domain   = c.Domain;

                    if (frm.ShowDialog(this) == DialogResult.OK)
                    {
                        SecurityPrincipal p = frm.Principal;

                        AuthenticationCredentials creds = new AuthenticationCredentials(frm.Username, frm.Domain, frm.Password);

                        _credentials[p] = creds;
                        UpdateCredentials();
                        OnCredentialsUpdated();
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;
            HttpResponseCancellationToken cancellationToken = new HttpResponseCancellationToken(response);
            NameValueCollection           requestParameters = context.Request.QueryString;
            SecurityPrincipal             securityPrincipal = context.User as SecurityPrincipal;

            response.ClearContent();
            response.Clear();
            response.AddHeader("Content-Type", CsvContentType);
            response.AddHeader("Content-Disposition", "attachment;filename=" + GetModelFileName(requestParameters["ModelName"]));
            response.BufferOutput = true;

            try
            {
                CopyModelAsCsvToStream(securityPrincipal, requestParameters, response.OutputStream, response.Flush, cancellationToken);
            }
            catch (Exception ex)
            {
                LogExceptionHandler?.Invoke(ex);
                throw;
            }
            finally
            {
                response.End();
            }
        }
Exemple #13
0
        /// <summary>
        /// Updates the system fields.
        /// </summary>
        /// <param name="targetContext">The target context.</param>
        /// <param name="targetItem">The target item.</param>
        /// <param name="sourceItem">The source item.</param>
        protected ListItem UpdateSystemFields(ClientContext targetContext, ListItem targetItem, ListItem sourceItem)
        {
            Logger.Log("Into UpdateSystemFields for " + sourceItem.DisplayName);

            if (sourceItem != null && targetItem != null)
            {
                try
                {
                    var            securityPrincipal = new SecurityPrincipal(Logger, RetryCount, Delay);
                    FieldUserValue author            = securityPrincipal.GetTargetUserFromUserMapping(targetContext, ((FieldUserValue)sourceItem[Constants.Author]));
                    FieldUserValue editor            = securityPrincipal.GetTargetUserFromUserMapping(targetContext, ((FieldUserValue)sourceItem[Constants.Editor]));

                    targetItem[Constants.Author]   = author; //authorUpn.Substring(authorUpn.LastIndexOf('|') + 1)
                    targetItem[Constants.Editor]   = editor; //((FieldUserValue)sourceItem["Editor"]).LookupValue
                    targetItem[Constants.Created]  = (DateTime)sourceItem[Constants.Created];
                    targetItem[Constants.Modified] = (DateTime)sourceItem[Constants.Modified];

                    //targetItem.Update();
                    targetItem.UpdateOverwriteVersion();
                    //targetContext.Load(targetItem);
                    //targetContext.ExecuteQuery();
                    targetContext.ExecuteQueryWithIncrementalRetry(RetryCount, Delay);
                }
                catch (Exception ex)
                {
                    Logger.LogError("Error in AddContent for " + sourceItem.DisplayName + Environment.NewLine + ex.Message);
                    //throw ex;
                }
            }

            return(targetItem);
        }
Exemple #14
0
        /// <summary>
        /// Evaluates if menu item should be visible to current user with access to <see cref="Roles"/>.
        /// </summary>
        /// <param name="parameter">
        /// Data used by the <see cref="MenuCommand"/>. If the <see cref="MenuCommand"/> does not require
        /// data to be passed, this object can be set to <c>null</c>.
        /// </param>
        /// <returns><c>true</c> if this <see cref="MenuCommand"/> can be executed; otherwise, <c>false</c>.</returns>
        public bool CanExecute(object parameter)
        {
            SecurityPrincipal currentPrincipal = CommonFunctions.CurrentPrincipal;

            return(currentPrincipal.Identity.IsAuthenticated &&
                   (string.IsNullOrEmpty(Roles) || Roles == "*" || currentPrincipal.IsInRole(Roles)));
        }
Exemple #15
0
        public IHttpActionResult CreateRecord(string modelName, [FromBody] JObject record)
        {
            // Proxy all other requests
            SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal;

            if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Administrator"))
            {
                return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized."));
            }


            using (DataContext dataContext = new DataContext("systemSettings"))
            {
                try
                {
                    Type   type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName);
                    object obj  = record.ToObject(type);

                    dataContext.Table(typeof(Meter).Assembly.GetType("SOE.Model." + modelName)).AddNewRecord(obj);
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.ToString()));
                }
            }

            return(Ok());
        }
Exemple #16
0
 private static void CachePrincipal(Guid sessionID, SecurityPrincipal principal)
 {
     if (s_authorizationCache.TryAdd(sessionID, principal))
     {
         SecurityProviderCache.AutoRefresh(principal.Identity.Provider);
     }
 }
Exemple #17
0
        public Form1()
        {
            InitializeComponent();
            rbacCombo1.SelectedIndex = 2;
            string        conStr = "DRIVER={MySQL ODBC 5.1 Driver};SERVER=192.168.10.3;PORT=3306;DATABASE=RBAC;USER=LT_DB;PASSWORD=She!byGT;OPTION=3";
            IDbConnection con    = (IDbConnection) new OdbcConnection(conStr);

            con.Open();

            try
            {
                //rbacButton1.GroupUniqueID = rbacButton1.GroupUniqueID;

                dbl = new DataLayer(con, DataLayer.DatabaseType.MySql);
                bool d = SecurityPrincipal.InitSecuritySystem(dbl, "Admin", "Admin");


                rbacButton1.oError            += new nKnight.RBACControl.OnRBACButtonError(rbacButton1_oError);
                rbacTextBox1.oError           += new nKnight.RBACControl.OnTextBoxError(rbacTextBox1_oError);
                rbacCheckBox1.oError          += new nKnight.RBACControl.OnRBACCheckBoxError(rbacCheckBox1_oError);
                rbacMaskedTextBox1.oError     += new nKnight.RBACControl.OnRBACMaskedTextBoxError(rbacMaskedTextBox1_oError);
                rbacRadioButton1.oError       += new nKnight.RBACControl.OnRBACRadioButtonError(rbacRadioButton1_oError);
                rbacCombo1.oError             += new nKnight.RBACControl.OnRBACCComboError(rbacCombo1_oError);
                rbacCheckListBox1.oError      += new nKnight.RBACControl.OnRBACCheckListBoxError(rbacCheckListBox1_oError);
                rbacLinkLabel1.oError         += new nKnight.RBACControl.OnRBACLinkLabelError(rbacLinkLabel1_oError);
                nKnightDateTimePicker1.oError += new nKnight.RBACControl.OnRBACDtPickerError(nKnightDateTimePicker1_oError);
                nKnightGridView1.oError       += new nKnight.RBACControl.OnRBACGridError(nKnightGridView1_oError);
                nKnightButton1.oError         += new nKnight.RBACControl.OnRBACButtonError(nKnightButton1_oError);
                nKnightRadioButton2.oError    += new nKnight.RBACControl.OnRBACRadioButtonError(nKnightRadioButton2_oError);
                //rbacButton1.Click += new EventHandler(rbacButton1_Click);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// Enables processing of HTTP web requests by a custom handler that implements the <see cref="IHostedHttpHandler"/> interface.
        /// </summary>
        /// <param name="request">HTTP request message.</param>
        /// <param name="response">HTTP response message.</param>
        /// <param name="cancellationToken">Propagates notification from client that operations should be canceled.</param>
        public Task ProcessRequestAsync(HttpRequestMessage request, HttpResponseMessage response, CancellationToken cancellationToken)
        {
            NameValueCollection requestParameters = request.RequestUri.ParseQueryString();

            response.Content = new PushStreamContent(async(stream, content, context) =>
            {
                try
                {
                    SecurityPrincipal securityPrincipal = request.GetRequestContext().Principal as SecurityPrincipal;
                    await CopyModelAsCsvToStreamAsync(securityPrincipal, requestParameters, stream, cancellationToken);
                }
                finally
                {
                    stream.Close();
                }
            }, new MediaTypeHeaderValue(CsvContentType));

            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = requestParameters["FileName"] ?? "Export.csv"
            };

#if MONO
            return(Task.FromResult(false));
#else
            return(Task.CompletedTask);
#endif
        }
Exemple #19
0
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            SecurityPrincipal securityPrincipal = filterContext.HttpContext.User as SecurityPrincipal;

            if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null)
            {
                filterContext.Result           = new HttpUnauthorizedResult($"Authentication failed for user \"{filterContext.HttpContext.User?.Identity.Name}\".");
                filterContext.HttpContext.User = null;
                return;
            }

            // Get current user name
            string username = securityPrincipal.Identity.Name;

            // Verify that the current thread principal has been authenticated.
            if (!securityPrincipal.Identity.IsAuthenticated)
            {
                filterContext.Result           = new HttpUnauthorizedResult($"User \"{username}\" is not authenticated.");
                filterContext.HttpContext.User = null;
            }
            else if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => securityPrincipal.IsInRole(role)))
            {
                filterContext.Result           = new HttpUnauthorizedResult($"Access is denied for user \"{username}\": minimum required roles = {AllowedRoles.ToDelimitedString(", ")}.");
                filterContext.HttpContext.User = null;
            }
            else
            {
                ThreadPool.QueueUserWorkItem(start => AuthorizationCache.CacheAuthorization(username, SecuritySettingsCategory));
            }
        }
Exemple #20
0
        /// <summary>
        /// Enables processing of HTTP web requests by a custom handler that implements the <see cref="IHostedHttpHandler"/> interface.
        /// </summary>
        /// <param name="request">HTTP request message.</param>
        /// <param name="response">HTTP response message.</param>
        /// <param name="cancellationToken">Propagates notification from client that operations should be canceled.</param>
        public Task ProcessRequestAsync(HttpRequestMessage request, HttpResponseMessage response, CancellationToken cancellationToken)
        {
            NameValueCollection requestParameters = request.RequestUri.ParseQueryString();

            response.Content = new PushStreamContent((stream, content, context) =>
            {
                try
                {
                    SecurityPrincipal securityPrincipal = request.GetRequestContext().Principal as SecurityPrincipal;
                    CopyModelAsCsvToStream(securityPrincipal, requestParameters, stream, null, cancellationToken);
                }
                catch (Exception ex)
                {
                    LogExceptionHandler?.Invoke(ex);
                    throw;
                }
                finally
                {
                    stream.Close();
                }
            },
                                                     new MediaTypeHeaderValue(CsvContentType));

            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = GetModelFileName(requestParameters["ModelName"])
            };

#if MONO
            return(Task.FromResult(false));
#else
            return(Task.CompletedTask);
#endif
        }
Exemple #21
0
        public GetAuthenticationCredentialsForm(SecurityPrincipal principal)
        {
            InitializeComponent();
            comboBoxSaveType.SelectedIndex = 0;

            lblDescription.Text = String.Format(Properties.Resources.GetAuthenticationCredentialsForm_TitleFormat,
                                                principal.Name, principal.Realm);
        }
        public void Initialize_WithUser()
        {
            var principal = new SecurityPrincipal("TheUser", null, null, null);

            Assert.That(principal.User, Is.EqualTo("TheUser"));
            Assert.That(principal.Role, Is.Null);
            Assert.That(principal.SubstitutedUser, Is.Null);
            Assert.That(principal.SubstitutedRole, Is.Null);
        }
        public static void SignIn(UserModel user, AccessTokenModel token)
        {
            var principal = new SecurityPrincipal(new GenericIdentity(token.UserName), new string[] { "Roles" });

            principal.Access.User  = user;
            principal.Access.Token = token;

            Thread.CurrentPrincipal = principal;
        }
Exemple #24
0
        public userManagement()
        {
            InitializeComponent();
            IDbConnection con = (IDbConnection) new OdbcConnection(conStr);

            con.Open();

            dbl = new DataLayer(con, DataLayer.DatabaseType.MySql);
            bool d = SecurityPrincipal.InitSecuritySystem(dbl, "Admin", "Admin");
        }
Exemple #25
0
        public IHttpActionResult GetRecords(string id, string modelName)
        {
            // Proxy all other requests
            SecurityPrincipal securityPrincipal = RequestContext.Principal as SecurityPrincipal;

            if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null || !securityPrincipal.IsInRole("Viewer,Administrator"))
            {
                return(BadRequest($"User \"{RequestContext.Principal?.Identity.Name}\" is unauthorized."));
            }


            object record;

            string idList = "";

            try
            {
                if (id != "all")
                {
                    string[] ids = id.Split(',');

                    if (ids.Count() > 0)
                    {
                        idList = $"ID IN ({ string.Join(",", ids.Select(x => int.Parse(x)))})";
                    }
                }
            }
            catch (Exception)
            {
                return(BadRequest("The id field must be a comma separated integer list."));
            }

            using (DataContext dataContext = new DataContext("systemSettings"))
            {
                try
                {
                    Type type = typeof(Meter).Assembly.GetType("SOE.Model." + modelName);

                    if (idList.Length == 0)
                    {
                        record = dataContext.Table(type).QueryRecords();
                    }
                    else
                    {
                        record = dataContext.Table(type).QueryRecordsWhere(idList);
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.ToString()));
                }
            }

            return(Ok(record));
        }
        /// <summary>
        /// Called once by common code after initialization. If an authentication middle-ware
        /// responds directly to specifically known paths it must override this virtual,
        /// compare the request path to it's known paths, provide any response information
        /// as appropriate, and true to stop further processing.
        /// </summary>
        /// <returns>
        /// Returning false will cause the common code to call the next middle-ware in line.
        /// Returning true will cause the common code to begin the async completion journey
        /// without calling the rest of the middle-ware pipeline.
        /// </returns>
        public override async Task <bool> InvokeAsync()
        {
            // Use Cases:
            //
            //  (1) Access resource marked as anonymous - let pipeline continue
            //  (2) Access resource as authenticated user - let pipeline continue
            //  --- remaining use cases are unauthorized ---
            //  (3) Access resource as result of a redirect from the OIDC Auth Server
            //  (4) Access resource marked for auth failure redirection - respond with 302 and abort pipeline
            //  (5) Access all other resources - respond with 401 and abort pipeline
            SecurityPrincipal securityPrincipal = Request.User as SecurityPrincipal;
            string            urlPath           = Request.Path.Value;

            // If the resources contains a code make an Attempt to Authorize via OIDC Auth server
            NameValueCollection queryParameters = System.Web.HttpUtility.ParseQueryString(Request.QueryString.Value);

            bool useAlternateSecurityProvider = Options.IsAlternateSecurityProviderResource(Request.Path.Value);

            useAlternateSecurityProvider = useAlternateSecurityProvider || (Options.AuthTestPage == Request.Path.Value && Request.QueryString.HasValue && queryParameters.AllKeys.Contains("useAlternate"));

            if (Request.User is not null && Request.User.IsInRole("logout"))
            {
                string identityName = Request.User.Identity.Name;

                string bodyMessage = Guid.TryParse(identityName, out Guid sessionID) && LogOut(sessionID)
                    ? "Logout complete"
                    : "Unable to locate the user session";

                using TextWriter writer = new StreamWriter(Response.Body, Encoding.UTF8, 4096, true);
                await writer.WriteAsync(bodyMessage);

                Response.StatusCode = 200;
                return(true); // Abort pipeline
            }

            // If the user is properly Authenticated but a redirect is requested send that redirect
            if (securityPrincipal?.Identity.IsAuthenticated == true && securityPrincipal.Identity.Provider.IsRedirectRequested)
            {
                Response.Redirect(securityPrincipal.Identity.Provider.RequestedRedirect ?? "/");
                return(true);
            }

            // If request is for an anonymous resource or user is properly authenticated, allow
            // request to propagate through the Owin pipeline
            if (Options.IsAnonymousResource(urlPath) || securityPrincipal?.Identity.IsAuthenticated == true)
            {
                return(false); // Let pipeline continue
            }
            // Abort pipeline with appropriate response
            if (Options.IsAuthFailureRedirectResource(urlPath) && !IsAjaxCall())
            {
                byte[] pathBytes;
                string base64Path, encodedPath, referrer = null;

                if (Request.Headers.TryGetValue("Referer", out string[] values) && values.Length == 1)
        public void Initialize_WithUserAndRoleAndSubstitutedUserAndSubstitedRole()
        {
            var role            = new SecurityPrincipalRole("TheGroup", null);
            var substitutedRole = new SecurityPrincipalRole("SomeGroup", null);
            var principal       = new SecurityPrincipal("TheUser", role, "SomeUser", substitutedRole);

            Assert.That(principal.User, Is.EqualTo("TheUser"));
            Assert.That(principal.Role, Is.SameAs(role));
            Assert.That(principal.SubstitutedUser, Is.EqualTo("SomeUser"));
            Assert.That(principal.SubstitutedRole, Is.SameAs(substitutedRole));
        }
Exemple #28
0
        private void SecureForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Don't proceed if the form is opened in design mode
                if (DesignMode)
                {
                    return;
                }

                // Check if the resource is excluded from being secured
                string resource = GetResourceName();

                if (!SecurityProviderUtility.IsResourceSecurable(resource))
                {
                    return;
                }

                // Set up security provider for passthrough authentication
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(WindowsIdentity.GetCurrent().Name);
                securityProvider.PassthroughPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                securityProvider.Authenticate();

                // Setup the security principal for role-based security
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                SecurityPrincipal = new SecurityPrincipal(securityIdentity);

                // Verify that the current thread principal has been authenticated
                if (!SecurityPrincipal.Identity.IsAuthenticated)
                {
                    throw new SecurityException($"Authentication failed for user '{SecurityPrincipal.Identity.Name}'");
                }

                // Perform a top-level permission check on the resource being accessed
                if (!SecurityProviderUtility.IsResourceAccessible(resource, SecurityPrincipal))
                {
                    throw new SecurityException($"Access to '{resource}' is denied");
                }

                // Set up the current thread principal
                // NOTE: Provided for backwards compatibility;
                //       recommended to use the SecurityPrincipal instead
                Thread.CurrentPrincipal = SecurityPrincipal;
            }
            catch (Exception ex)
            {
                if (ExceptionHandler is null)
                {
                    throw;
                }

                ExceptionHandler(ex);
            }
        }
Exemple #29
0
        /// <summary>
        /// Manages the security principal.
        /// </summary>
        /// <param name="targetContext">The target context.</param>
        /// <param name="targetItem">The target item.</param>
        /// <param name="targetWeb">The target web.</param>
        /// <param name="sourceItemRoleAssignment">The source item role assignment.</param>
        private void ManageSecurityPrincipal(ClientContext targetContext, ListItem targetItem, Web targetWeb, RoleAssignment sourceItemRoleAssignment)
        {
            if (sourceItemRoleAssignment != null)
            {
                Task log = Logger.Log("Into ManageSecurityPrincipal for " + sourceItemRoleAssignment.Member);

                try
                {
                    var raMember      = sourceItemRoleAssignment.Member;
                    var principalType = raMember.PrincipalType;
                    var roleType      = sourceItemRoleAssignment.RoleDefinitionBindings[0].RoleTypeKind;

                    SecurityPrincipal securityPrincipal = new SecurityPrincipal(Logger, RetryCount, Delay);

                    var task = Task.Run(() =>
                    {
                        Principal principal = securityPrincipal.GetSecurityPrincipal(targetContext, raMember, principalType);
                        if (principal != null)
                        {
                            securityPrincipal.SetSecurityPrincipal(targetContext, targetItem, targetWeb, roleType, principal);
                        }
                        else
                        {
                            Logger.LogWarning("Security principal not found for " + raMember.LoginName +
                                              Environment.NewLine +
                                              "Item affected: " +
                                              targetItem.DisplayName);
                        }
                    });

                    task.Wait();
                    if (task.Status == TaskStatus.RanToCompletion)
                    {
                        Logger.Log("Permission migration completed for " + targetItem.DisplayName);
                    }
                    else
                    {
                        Logger.LogError("Permission migration did not complete properly for " + targetItem.DisplayName +
                                        Environment.NewLine +
                                        "Task Status" +
                                        task.Status.ToString());
                    }
                }
                catch (Exception ex)
                {
                    log = Logger.LogError("Error in ManageSecurityPrincipal for " + sourceItemRoleAssignment.Member +
                                          Environment.NewLine +
                                          ex.Message);
                    //throw ex;
                }
            }
        }
Exemple #30
0
        public static bool Login(string username, string password)
        {
            var userInfo = Auth.Authenticate(username, password);

            if (userInfo == null)
            {
                errorLogger.SaveError(0, 1, 1, 2, "Login Attempt", "Warehouse", new InvalidCredentialException("Invalid credentials, Username = "******"Login Window", "Successful Login");
            return(true);
        }
        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>A string array containing the names of all the roles stored in the data source for the configured applicationName.</returns>
        public override string[] GetAllRoles()
        {
            // Get all the groups in Active Directory.
            List<System.DirectoryServices.Protocols.SearchResultEntry> entries = ad.GetEntries("(objectCategory = group)");

            // Check that entries were returned.
            if (entries != null)
            {
                // There are entries in the list.

                // Create a list to hold the names of the roles found.
                List<string> roleNames = new List<string>();

                // Create groups from the entries.
                foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in entries)
                {
                    SecurityPrincipal securityPrincipal = new SecurityPrincipal(ad, entry);
                    roleNames.Add(securityPrincipal.SAMAccountName);
                }

                return roleNames.ToArray();
            }
            else
            {
                // No entries were returned.
                return new string[] { };
            }
        }
 public override void ExplicitVisit(SecurityPrincipal fragment)
 {
     _fragments.Add(fragment);
 }
Exemple #33
0
 public override void Visit(SecurityPrincipal node) { this.action(node); }
        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>A string array containing the names of all the roles stored in the data source for the configured applicationName.</returns>
        public override string[] GetAllRoles()
        {
            // Create a wildcard group name that corresponds to groups maintained by this application.
            string wildcardGroupName = GetGroupName("*");

            // Search Active Directory for groups corresponding to roles managed by this application.
            List<System.DirectoryServices.Protocols.SearchResultEntry> entries = ad.GetEntriesBySAMAccountName(wildcardGroupName);

            // Check that entries were returned.
            if (entries != null)
            {
                // There are entries in the list.

                // Create a list to hold the names of the roles found.
                List<String> roleNames = new List<String>();

                // Create groups from the entries.
                foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in entries)
                {
                    SecurityPrincipal securityPrincipal = new SecurityPrincipal(ad, entry);
                    if (securityPrincipal.IsGroup)
                    {
                        // Get the name of the role from the group name.
                        roleNames.Add(GetRoleName(securityPrincipal.SAMAccountName));
                    }
                }

                return roleNames.ToArray();
            }
            else
            {
                // No entries were returned.
                return new string[] { };
            }
        }