Exemple #1
0
        public User getUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");
            User userToReturn = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    // Save the original HttpContext and set it to null
                    // solution to enable impersonated access to UPS from here:
                    // https://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
                    HttpContext savedHttpContext = HttpContext.Current;
                    HttpContext.Current          = null;

                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to UserProfileManager obtained");
                        UserProfile userProfile = userProfileManager.GetUserProfile(new Guid(guid));
                        if (userProfile == null)
                        {
                            UPSBrowserLogger.LogError(loggingCategory, $"User profile with guid {guid} not found in User Profile Service");
                            return; //exit delegate block
                        }
                        ;

                        UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}");

                        userToReturn        = UserProfileToUser(userProfile);
                        string outputString = $"Retrieved user properties - Email: {userToReturn.WorkEmail}, Username: {userToReturn.AccountName}, DisplayName: {userToReturn.DisplayName}, Department: {userToReturn.Department}, JobTitle: {userToReturn.JobTitle}";
                        UPSBrowserLogger.LogDebug(loggingCategory, outputString);
                    }
                    catch (System.Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    }
                    finally
                    {
                        // Restore HttpContext
                        HttpContext.Current = savedHttpContext;
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(userToReturn);
        }
Exemple #2
0
 private void InitUserProfilesDatasource()
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "InitUserProfilesDatasource invoked");
     UserProfilesDatasource                 = new ObjectDataSource();
     UserProfilesDatasource.ID              = UserProfiles_datasource_ID;
     UserProfilesDatasource.SelectMethod    = "GetFilteredUserProfiles";
     UserProfilesDatasource.TypeName        = this.GetType().AssemblyQualifiedName; // data access methods are in this same classs
     UserProfilesDatasource.ObjectCreating += new ObjectDataSourceObjectEventHandler(UserProfilesDatasource_ObjectCreating);
     this.Controls.Add(UserProfilesDatasource);
 }
Exemple #3
0
        private void ConfigureUserProfilesGridView()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ConfigureUserProfilesGridView invoked");

            UserProfilesGridView.Sorting           += new GridViewSortEventHandler(UserProfilesGridView_Sorting);
            UserProfilesGridView.PageIndexChanging += new GridViewPageEventHandler(UserProfilesGridView_PageIndexChanging);
            UserProfilesGridView.RowDataBound      += new GridViewRowEventHandler(UserProfilesGridView_RowDataBound);
            UserProfilesGridView.PagerTemplate      = null;
            UserProfilesGridView.PageSize           = 10;
        }
Exemple #4
0
        public List <IdentityProvider> getIdentityProviders()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked");
            List <IdentityProvider> identityProvidersToReturn = new List <IdentityProvider>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    try
                    {
                        SPContext spContext                  = Microsoft.SharePoint.SPContext.Current;
                        SPWebApplication webApp              = spContext.Site.WebApplication;
                        SPUrlZone spUrlZone                  = spContext.Site.Zone;
                        SPIisSettings spIisSettings          = webApp.GetIisSettingsWithFallback(spUrlZone);
                        SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local;

                        foreach (SPAuthenticationProvider prov in spIisSettings.ClaimsAuthenticationProviders)
                        {
                            if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
                            {
                                var lp =
                                    from SPTrustedLoginProvider spt in
                                    sptMgr.TrustedLoginProviders
                                    where spt.DisplayName == prov.DisplayName
                                    select spt;

                                if ((lp != null) && (lp.Count() > 0))
                                {
                                    SPTrustedLoginProvider loginProv = lp.First();
                                    identityProvidersToReturn.Add(new IdentityProvider
                                    {
                                        Name        = loginProv.Name,
                                        DisplayName = loginProv.DisplayName,
                                        Description = loginProv.Description,
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(identityProvidersToReturn);
        }
Exemple #5
0
        public List <TokenSigningCertificate> getTokenSigningCertificates()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "TokenSigningCertificatesHelper.getTokenSigningCertificates invoked");
            List <TokenSigningCertificate> certsToReturn = new List <TokenSigningCertificate>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    try
                    {
                        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                        UPSBrowserLogger.LogDebug(loggingCategory, "LocalMachine cert store open");

                        SPContext spContext = Microsoft.SharePoint.SPContext.Current;
                        string siteHostName = (new Uri(spContext.Site.Url)).Host.ToLower();

                        UPSBrowserLogger.LogDebug(loggingCategory, $"Current SP site URL host part: {siteHostName}");

                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            UPSBrowserLogger.LogDebug(loggingCategory, $"cert.FriendlyName: {cert.FriendlyName}, cert.HasPrivateKey: {cert.HasPrivateKey}, cert.NotAfter: {cert.NotAfter}");
                            if (cert.HasPrivateKey && (cert.NotAfter > DateTime.Now))
                            {
                                TokenSigningCertificate certToAdd = new TokenSigningCertificate
                                {
                                    friendlyName = cert.FriendlyName,
                                    subject      = cert.Subject,
                                    thumbprint   = cert.Thumbprint,
                                    rank         = cert.Subject.ToLower().Equals($"cn={siteHostName}") ? 1 : 0,
                                    cert         = cert
                                };
                                certsToReturn.Add(certToAdd);
                                UPSBrowserLogger.LogDebug(loggingCategory, $"Cert added - friendly name: {certToAdd.friendlyName}; subject: {certToAdd.subject}, rank: {certToAdd.rank}");
                            }
                            ;
                        }
                    }
                    catch (Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(certsToReturn.OrderByDescending(cert => cert.rank).ToList());
        }
Exemple #6
0
        private void InitImportUsersSearchResultsDatasource()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "InitImportUsersSearchResultsDatasource invoked");

            ImportUsersSearchResultsDatasource                 = new ObjectDataSource();
            ImportUsersSearchResultsDatasource.ID              = ImportUsersSearchResults_datasource_ID;
            ImportUsersSearchResultsDatasource.SelectMethod    = "GetFilteredExternalUsers";
            ImportUsersSearchResultsDatasource.TypeName        = this.GetType().AssemblyQualifiedName; // data access methods are in this same classs
            ImportUsersSearchResultsDatasource.ObjectCreating += new ObjectDataSourceObjectEventHandler(ImportUsersSearchResultsDatasource_ObjectCreating);
            this.Controls.Add(ImportUsersSearchResultsDatasource);
        }
Exemple #7
0
        public string getAccountNameForEmail(string email, string indentityProviderName)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"email: {email}, indentityProviderName: {indentityProviderName}");
            string originalIssuer      = SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, indentityProviderName);
            SPClaimProviderManager mgr = SPClaimProviderManager.Local;
            SPClaim claim       = new SPClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", email, System.Security.Claims.ClaimValueTypes.String, originalIssuer);
            string  accountName = mgr.EncodeClaim(claim);

            return(accountName);
        }
Exemple #8
0
        void DisplayCriticalError(string errorMessage, bool showBackButton)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "DisplayCriticalError invoked");

            MainViewTabButton.Visible    = false;
            ImportUsersTabButton.Visible = false;
            SettingsTabButton.Visible    = false;

            CriticalErrorMessage.Text          = errorMessage;
            CriticalErrorBackButton.Visible    = showBackButton;
            MultiViewContainer.ActiveViewIndex = 3;
        }
Exemple #9
0
        public User createUser(User newUser, string identityProviderName)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "createUser invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"newUser.UserGuid: {newUser.UserGuid}");
            newUser.UserGuid = Guid.NewGuid().ToString();
            _users.Add(newUser);

            // log completed activity
            //UPSBrowserLogger.LogActivity(newUser.Username, UPSBrowserLogger.LogActivityActionEnum.Create, UPSBrowserLogger.LogActivityResultEnum.Success);
            ActivityLogger.LogActivity(newUser.AccountName, LogActivityActionEnum.Create, LogActivityResultEnum.Success);
            return(newUser);
        }
Exemple #10
0
        private void SaveSettingsButton_Click(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "SaveSettingsButton_Click invoked");

            UPSBrowserSettings.setStringProperty(settings, "identityProviderName", IdentityProvidersDropDownList.SelectedValue);
            UPSBrowserSettings.setStringProperty(settings, "tokenSigningCertificateThumbprint", TokenSigningCertificatesDropDownList.SelectedValue);
            UPSBrowserSettings.setStringProperty(settings, "wsExternalUsersSourceUrl", WSExternalUsersSourceURLTextBox.Text);

            bool result = SaveSettings();

            if (!result)
            {
                DisplayCriticalError("Error saving settings!", true);
            }
        }
Exemple #11
0
        public User getUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");
            User userToReturn = _users.SingleOrDefault(user => user.UserGuid == guid);

            if (userToReturn == null)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"User profile not found");
                return(null);
            }

            UPSBrowserLogger.LogDebug(loggingCategory, $"userToReturn.AccountName: {userToReturn.AccountName}, userToReturn.WorkEmail: {userToReturn.WorkEmail}");
            return(userToReturn);
        }
Exemple #12
0
        public upsbrowser() : base()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "upsbrowser constructor invoked");

            //upsUsersDAL = FakeUPSUsersDAL.getInstance();
            upsUsersDAL = new UPSUsersDAL();

            //externalUsersSource = FakeWSExternalUsersSource.getInstance();
            externalUsersSource = new WSExternalUsersSource();

            identityProvidersHelper = new IdentityProvidersHelper();
            certsHelper             = new TokenSigningCertificatesHelper();

            LoadSettings();
        }
Exemple #13
0
        public List <User> getUsersBySearchString(string searchString)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUsersBySearchString invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"_users.Count: {_users.Count}");

            if (searchString.Length < 3)
            {
                return(null);
            }

            List <User> usersToReturn = _users.Where((user) => String.Concat(user.WorkEmail, user.AccountName, "|", user.FirstName, " ", user.LastName, "|", user.DisplayName).ToLower().Contains(searchString.ToLower())).ToList <User>();

            UPSBrowserLogger.LogDebug(loggingCategory, $"usersToReturn.Count: {usersToReturn.Count}");
            return(usersToReturn);
        }
Exemple #14
0
        private void ImportUsersStartImportButton_Click(object sender, EventArgs evt)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersStartImportButton_Click invoked");

            string        resolvedUsersEmails = upsbrowser_import_users_resolved_hiddeninput.Text;
            List <string> emails = new List <string>(resolvedUsersEmails.Split(';'));

            emails = emails.Where(email => !string.IsNullOrEmpty(email)).ToList <string>(); //filter out empty emails

            string wsBaseUrl             = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
            string certThumbprint        = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");
            string identityProviderName  = UPSBrowserSettings.getStringProperty(this.settings, "identityProviderName");
            TokenSigningCertificate cert = certs.FirstOrDefault(c => c.thumbprint == certThumbprint);

            List <User> users = null;

            try
            {
                externalUsersSource.Init(wsBaseUrl, cert);
                users = externalUsersSource.getUsersByEmails(emails);
            }
            catch (Exception e)
            {
                DisplayCriticalError($"Error getting users from external source: {e.Message}", true);
                return;
            };


            if ((users != null) && (users.Count > 0))
            {
                foreach (User user in users)
                {
                    User createdUser = upsUsersDAL.createUser(user, identityProviderName);
                    if (createdUser != null)
                    {
                        string hiddenInputValue = upsbrowser_import_users_resolved_hiddeninput.Text.ToLower();
                        hiddenInputValue = hiddenInputValue.Replace(createdUser.WorkEmail.ToLower() + ";", "");
                        upsbrowser_import_users_resolved_hiddeninput.Text = hiddenInputValue;
                    }
                }
                ;
            }
            ;
        }
Exemple #15
0
        void UserProfilesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "UserProfilesGridView_RowDataBound invoked");

            // If it is not a DataRow then return.
            if (e.Row.RowType != DataControlRowType.DataRow)
            {
                return;
            }

            DataRowView dataView = (DataRowView)e.Row.DataItem;
            string      userGuid = dataView["UserGuid"].ToString();

            UPSBrowserLogger.LogDebug(loggingCategory, $"userGuid: {userGuid}");

            TableCell hyperLinkCell = e.Row.Cells[0];
            HyperLink hyperLink     = hyperLinkCell.Controls[0] as HyperLink;

            hyperLink.NavigateUrl = $"javascript:upsbrowser.openUPSUserEditForm('{userGuid}')";
        }
Exemple #16
0
        public List <User> getUsersByEmails(List <string> emails)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "WSExternalUsersSource.getUsersByEmails invoked");

            string jsonString = JsonConvert.SerializeObject(emails);

            string path       = $"getusersbyemails";
            string body       = jsonString;
            string jsonResult = callJsonWebService(path, true, null, body);

            if (string.IsNullOrEmpty(jsonResult))
            {
                return(null);
            }
            ;

            List <User> usersToReturn = JsonConvert.DeserializeObject <List <User> >(jsonResult);

            return(usersToReturn);
        }
Exemple #17
0
        void ImportUsersSearchResultsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "UserProfilesGridView_RowDataBound invoked");

            // If it is not DataRow then return.
            if (e.Row.RowType != DataControlRowType.DataRow)
            {
                return;
            }

            DataRowView dataView  = (DataRowView)e.Row.DataItem;
            string      userEmail = dataView["WorkEmail"].ToString();

            UPSBrowserLogger.LogDebug(loggingCategory, $"userEmail: {userEmail}");

            TableCell hyperLinkCell = e.Row.Cells[0];
            HyperLink hyperLink     = hyperLinkCell.Controls[0] as HyperLink;

            hyperLink.NavigateUrl = $"javascript:upsbrowser.addExternalUserToResolvedList('{userEmail}')";
        }
Exemple #18
0
        private void ConfigureUserProfilesGridViewColumns()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ConfigureUserProfilesGridViewColumns invoked");


            HyperLinkField col1 = new HyperLinkField();

            col1.HeaderText     = "Display Name";
            col1.DataTextField  = "DisplayName";
            col1.SortExpression = "DisplayName";
            UserProfilesGridView.Columns.Add(col1);

            SPBoundField col2 = new SPBoundField();

            col2.HeaderText     = "Account Name";
            col2.DataField      = "AccountName";
            col2.SortExpression = "AccountName";
            UserProfilesGridView.Columns.Add(col2);

            SPBoundField col3 = new SPBoundField();

            col3.HeaderText     = "Job title";
            col3.DataField      = "JobTitle";
            col3.SortExpression = "JobTitle";
            UserProfilesGridView.Columns.Add(col3);

            SPBoundField col4 = new SPBoundField();

            col4.HeaderText     = "Department";
            col4.DataField      = "Department";
            col4.SortExpression = "Department";
            UserProfilesGridView.Columns.Add(col4);


            SPBoundField col5 = new SPBoundField();

            col5.HeaderText = "User guid";
            col5.DataField  = "UserGuid";
            UserProfilesGridView.Columns.Add(col5);
        }
Exemple #19
0
        public bool deleteUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "deleteUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");
            User userToDelete = _users.SingleOrDefault(user => user.UserGuid == guid);

            if (userToDelete == null)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"User profile not found");
                //UPSBrowserLogger.LogActivity(userToDelete.Username, UPSBrowserLogger.LogActivityActionEnum.Delete, UPSBrowserLogger.LogActivityResultEnum.Error);
                ActivityLogger.LogActivity(userToDelete.AccountName, LogActivityActionEnum.Delete, LogActivityResultEnum.Error);
                return(false);
            }

            UPSBrowserLogger.LogDebug(loggingCategory, $"userToDelete.AccountName: {userToDelete.AccountName}, userToDelete.WorkEmail: {userToDelete.WorkEmail}");
            _users.Remove(userToDelete);
            UPSBrowserLogger.LogDebug(loggingCategory, "User profile deleted");
            //UPSBrowserLogger.LogActivity(userToDelete.Username, UPSBrowserLogger.LogActivityActionEnum.Delete, UPSBrowserLogger.LogActivityResultEnum.Success);
            ActivityLogger.LogActivity(userToDelete.AccountName, LogActivityActionEnum.Delete, LogActivityResultEnum.Success);

            return(true);
        }
Exemple #20
0
        private void CloseForm()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "CloseFormWithParentRefresh invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"needParentRefreshing: {needParentRefreshing}");

            StringBuilder sb = new StringBuilder();

            sb.Append("<script type='text/javascript'>");
            if (needParentRefreshing)
            {
                sb.Append("SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, null);");
                sb.Append("window.top.location.href = window.top.location.href;");
            }
            else
            {
                sb.Append("SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, null);");
            }
            sb.Append("</script>");

            ClientScriptManager cs = Page.ClientScript;

            cs.RegisterStartupScript(this.GetType(), "UPSBROWSER_SCRIPT_CLOSE_MODAL", sb.ToString());
        }
Exemple #21
0
        private void ImportUsersTabButton_Click(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersTabButton_Click invoked");

            bool validSettings = ValidateSettings();

            if (!validSettings)
            {
                string message = (userAccessLevel == UserAccessLevels.Admin) ?
                                 "Please set all required parameters on the Settings tab and reload the page!"
                    :
                                 "Use farm administrator account to set all required parameters on the Settings tab and reload the page!";

                DisplayCriticalError(message, true);
                return;
            }


            MainViewTabButton.CssClass         = "kcell-upsbrowser-tabbutton";
            ImportUsersTabButton.CssClass      = "kcell-upsbrowser-tabbutton--clicked";
            SettingsTabButton.CssClass         = "kcell-upsbrowser-tabbutton";
            MultiViewContainer.ActiveViewIndex = 1;
        }
Exemple #22
0
        private bool InitSettings()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "InitSettings invoked");

            // get the list of certificates installed on SharePoint server to select one of them for token signing
            certs = certsHelper.getTokenSigningCertificates();

            if (userAccessLevel != UserAccessLevels.Admin)
            {
                SettingsTabButton.Visible = false;
                return(true);
            }

            List <IdentityProvider> identityProviders = identityProvidersHelper.getIdentityProviders();

            if (identityProviders == null || identityProviders.Count == 0)
            {
                UPSBrowserLogger.LogError(loggingCategory, "Cannot get the list of identity providers");
                return(false);
            }

            if (!IsPostBack)
            {
                IdentityProvidersDropDownList.Items.Add(new ListItem("Select Identity Provider", ""));
                foreach (IdentityProvider identityProvider in identityProviders)
                {
                    IdentityProvidersDropDownList.Items.Add(new ListItem(identityProvider.DisplayName, identityProvider.Name));
                }
                ;

                string identityProviderName;
                try
                {
                    identityProviderName = this.identityProviderName;
                }
                catch
                {
                    identityProviderName = "";
                };

                ListItem listItem = IdentityProvidersDropDownList.Items.FindByValue(identityProviderName);
                if (listItem != null)
                {
                    IdentityProvidersDropDownList.SelectedValue = listItem.Value;
                }
                else
                {
                    IdentityProvidersDropDownList.SelectedValue = "";
                };
            }
            ;

            certs = certsHelper.getTokenSigningCertificates();
            if (certs == null || certs.Count == 0)
            {
                UPSBrowserLogger.LogError(loggingCategory, "No suitable certificates found to sign tokens for the external web service authentication");
                return(false);
            }

            if (!IsPostBack)
            {
                TokenSigningCertificatesDropDownList.Items.Add(new ListItem("Select certificate to use for token signing", ""));
                foreach (TokenSigningCertificate cert in certs)
                {
                    TokenSigningCertificatesDropDownList.Items.Add(new ListItem(cert.friendlyName, cert.thumbprint));
                }
                ;

                string   certThumbprint = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");
                ListItem listItem       = TokenSigningCertificatesDropDownList.Items.FindByValue(certThumbprint);
                if (listItem != null)
                {
                    TokenSigningCertificatesDropDownList.SelectedValue = listItem.Value;
                }
                else
                {
                    TokenSigningCertificatesDropDownList.SelectedValue = "";
                };
            }
            ;

            if (!IsPostBack)
            {
                string wsBaseUrl = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
                WSExternalUsersSourceURLTextBox.Text = wsBaseUrl;
            }
            ;

            return(true); //Ok
        }
Exemple #23
0
 private void UserFilterStartSearchButton_Click(object sender, EventArgs e)
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "UserFilterStartSearchButton_Click invoked");
     BindUserProfilesGridView();
 }
Exemple #24
0
        private void InitLatestActivitiesListView()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "InitLatestActivitiesListView invoked");

            Tuple <string, string> ensureListResult = ActivityLogger.EnsureActivitiesList(); //it resturns a Tuple <listGuid, viewGuid>

            if (ensureListResult == null)
            {
                string errorMessage = "ActivityLogger.EnsureActivitiesList returned null";
                UPSBrowserLogger.LogError(loggingCategory, errorMessage);
                throw new Exception(errorMessage);
            }

            string listGuid = ensureListResult.Item1;
            string viewGuid = ensureListResult.Item2;

            UPSBrowserLogger.LogDebug(loggingCategory, $"listGuid: {listGuid}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"viewGuid: {viewGuid}");

            Microsoft.SharePoint.WebPartPages.XsltListViewWebPart listViewWebPart = new Microsoft.SharePoint.WebPartPages.XsltListViewWebPart();
            listViewWebPart.ListId = new Guid(listGuid);

            listViewWebPart.Toolbar = "";

            string xmlDefinition = $@"
                <View Name=""{{{viewGuid}}}"" MobileView=""TRUE"" Type=""HTML"" Hidden=""TRUE"" DisplayName="""" Level=""1"" BaseViewID=""1"" ContentTypeID=""0x"" ImageUrl=""/_layouts/15/images/generic.png?rev=23"" >
                    <Query>
                        <OrderBy>
                            <FieldRef Name=""RegisteredDate"" Ascending=""FALSE""/>
                        </OrderBy>
                        <Where>
                            <Geq><FieldRef Name=""RegisteredDate""/><Value Type=""DateTime""><Today/></Value></Geq>
                        </Where>
                    </Query>
                    <ViewFields>
                        <FieldRef Name=""RegisteredDate""/>
                        <FieldRef Name=""Initiator""/>
                        <FieldRef Name=""User""/>
                        <FieldRef Name=""Action""/>
                        <FieldRef Name=""Result""/>
                        <FieldRef Name=""AdditionalInfo""/>
                    </ViewFields>
                    <RowLimit Paged=""TRUE"">30</RowLimit>
                    <Aggregations Value=""Off""/>
                    <JSLink>clienttemplates.js</JSLink>
                    <XslLink Default=""TRUE"">main.xsl</XslLink>
                    <Toolbar Type=""None""/>
                </View>
            ";

            listViewWebPart.XmlDefinition = xmlDefinition;

            listViewWebPart.AllowClose      = false;
            listViewWebPart.AllowConnect    = false;
            listViewWebPart.AllowEdit       = false;
            listViewWebPart.AllowHide       = false;
            listViewWebPart.AllowMinimize   = false;
            listViewWebPart.AllowZoneChange = false;
            listViewWebPart.ChromeType      = PartChromeType.None;
            PanelLatestActivities.Controls.Add(listViewWebPart);
        }
Exemple #25
0
 private void BindImportUsersSearchResultsGridView()
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "BindImportUsersSearchResultsGridView invoked");
     ImportUsersSearchResultsGridView.DataSourceID = ImportUsersSearchResults_datasource_ID;
     ImportUsersSearchResultsGridView.DataBind();
 }
Exemple #26
0
        public DataTable GetFilteredExternalUsers()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "GetFilteredExternalUsers invoked");

            string searchString   = upsbrowser_import_users_searchtextbox.Text;
            string wsBaseUrl      = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
            string certThumbprint = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");

            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"wsBaseUrl: {wsBaseUrl}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"certThumbprint: {certThumbprint}");

            UPSBrowserLogger.LogDebug(loggingCategory, $"certs == null: {certs == null}");
            TokenSigningCertificate cert = certs.FirstOrDefault(c => c.thumbprint == certThumbprint);

            UPSBrowserLogger.LogDebug(loggingCategory, $"cert == null: {cert == null}");

            if (
                string.IsNullOrEmpty(searchString)
                ||
                searchString.Length < Constants.searchStringMingLength
                ||
                string.IsNullOrEmpty(wsBaseUrl)
                ||
                cert == null
                )
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Invalid searchString, wsBaseUrl or cert. Returning null.");
                return(null);
            }

            List <User> externalUsers = null;

            try
            {
                externalUsersSource.Init(wsBaseUrl, cert);
                externalUsers = externalUsersSource.getUsersBySearchString(searchString);
            }
            catch (Exception e)
            {
                DisplayCriticalError($"Error getting users from external source: {e.Message}", true);
                return(null);
            };

            if (externalUsers == null)
            {
                return(null);
            }
            ;

            DataTable dt = new DataTable();

            dt.Columns.Add("DisplayName");
            dt.Columns.Add("WorkEmail");
            dt.Columns.Add("JobTitle");
            dt.Columns.Add("Department");

            externalUsers.ForEach((externalUser) => {
                DataRow dr        = dt.NewRow();
                dr["DisplayName"] = externalUser.DisplayName;
                dr["WorkEmail"]   = externalUser.WorkEmail;
                dr["JobTitle"]    = externalUser.JobTitle;
                dr["Department"]  = externalUser.Department;
                dt.Rows.Add(dr);
            });

            return(dt);
        }
Exemple #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "Page_Load invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"IsPostBack: {IsPostBack}");

            userAccessLevel = CheckUserAccess();
            UPSBrowserLogger.LogDebug(loggingCategory, $"userAccessLevel: {userAccessLevel}");
            if (userAccessLevel == UserAccessLevels.None)
            {
                DisplayCriticalError("Access denied. Use farm administrator account to configure the list of allowed users using the provided UPSBrowser-AddUser.ps1 script", false);
                return;
            }
            ;

            bool result = InitSettings();

            if (!result)
            {
                DisplayCriticalError("Cannot initialize settings tab!", true);
                return;
            }

            InitLatestActivitiesListView();

            ConfigureUserProfilesGridView();
            ConfigureImportUsersSearchResultsGridView();
            if (!IsPostBack)
            {
                ConfigureUserProfilesGridViewColumns();
                ConfigureImportUsersSearchResultsGridViewColumns();

                MainViewTabButton.CssClass         = "kcell-upsbrowser-tabbutton--clicked";
                MultiViewContainer.ActiveViewIndex = 0;
            }
            ;

            InitUserProfilesDatasource();
            BindUserProfilesGridView();

            InitImportUsersSearchResultsDatasource();

            UserFilterStartSearchButton.Click               += UserFilterStartSearchButton_Click;
            MainViewTabButton.Click                         += MainViewTabButton_Click;
            ImportUsersTabButton.Click                      += ImportUsersTabButton_Click;
            SettingsTabButton.Click                         += SettingsTabButton_Click;
            upsbrowser_import_users_searchbutton.Click      += ImportUsersSearchButton_Click;
            upsbrowser_import_users_startimportbutton.Click += ImportUsersStartImportButton_Click;
            SaveSettingsButton.Click                        += SaveSettingsButton_Click;

            UPSBrowserLogger.LogDebug(loggingCategory, $"identityProviderName: {identityProviderName}");

            if (!string.IsNullOrEmpty(identityProviderName))
            {
                AddUserProfileButton.OnClientClick = $"upsbrowser.openUPSUserEditForm('','{identityProviderName}');return false;";
                AddUserProfileButton.Enabled       = true;
            }
            else
            {
                AddUserProfileButton.Enabled = false;
            };
        }
Exemple #28
0
 private void ConfigureImportUsersSearchResultsGridView()
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "ConfigureImportUsersSearchResultsGridView invoked");
     ImportUsersSearchResultsGridView.Sorting      += new GridViewSortEventHandler(ImportUsersSearchResultsGridView_Sorting);
     ImportUsersSearchResultsGridView.RowDataBound += new GridViewRowEventHandler(ImportUsersSearchResultsGridView_RowDataBound);
 }
Exemple #29
0
        public string getTokenString(TokenSigningCertificate signingCertificate)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "TokenHelper.getTokenString invoked");


            // In .NET 4.5 which is the target framework version, DateTimeOffset does not have the ToUnixTimeSeconds method which was only introduced in .NET 4.6
            var dateNowUtc   = DateTime.UtcNow;
            var epoch        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var unixDateTime = (dateNowUtc - epoch).TotalSeconds + (Constants.jwtTokenLifetimeInMinutes * 60);


            var payload = new Dictionary <string, object>()
            {
                { "sub", signingCertificate.subject },
                { "friendlyName", signingCertificate.friendlyName },
                { "iss", signingCertificate.subject },
                { "aud", Constants.jwtTokenAudience },
                //{ "exp", DateTimeOffset.UtcNow.AddMinutes(Constants.jwtTokenLifetimeInMinutes).ToUnixTimeSeconds() }
                { "exp", unixDateTime }
            };
            string token = null;


            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                // If you get "Keyset does not exist" exception at this stage, make sure the the SP web app pool account has access to the private key of the selected cert
                UPSBrowserLogger.LogDebug(loggingCategory, "Trying to get the cert's private key...");
                var rsaCryptoServiceProvider = signingCertificate.cert.PrivateKey as RSACryptoServiceProvider;


                try
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Trying to generate a JWT token string using the private key...");
                    token = Jose.JWT.Encode(payload, rsaCryptoServiceProvider, JwsAlgorithm.RS256);
                }
                catch (System.Security.Cryptography.CryptographicException cryptoException)
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "System.Security.Cryptography.CryptographicException catched");

                    // Look for "Invalid algorithm specified" exception -
                    UPSBrowserLogger.LogInfo(loggingCategory, $"cryptoException.Message: {cryptoException.Message}");

                    var privateKey = signingCertificate.cert.PrivateKey as RSACryptoServiceProvider;
                    bool privateKeyIsExportable = privateKey.CspKeyContainerInfo.Exportable;

                    if (privateKeyIsExportable)
                    {
                        UPSBrowserLogger.LogDebug(loggingCategory, $"Recreating RsaCryptoServiceProvider using the same cert with MS Enhanced CSP to enable SHA256");

                        // Re-create RsaCryptoServiceProvider using the same cert with MS Enhanced CSP to enable SHA256.
                        // This will only work if the private key of the cert is marked as exportable!
                        // The new RsaCryptoServiceProvider is created by exporting the original cert private key
                        // and re-importing it again, and the export operation will throw the exception if the original
                        // cert is not marked as exportable: "System.Security.Cryptography.CryptographicException: Key not valid for use in specified state."
                        RSACryptoServiceProvider rsaCryptoServiceProvider_MSEnchancedCSP = new RSACryptoServiceProvider();
                        rsaCryptoServiceProvider_MSEnchancedCSP.ImportParameters(privateKey.ExportParameters(true));

                        UPSBrowserLogger.LogDebug(loggingCategory, "Trying to generate a JWT token string again using the reimported private key...");
                        token = Jose.JWT.Encode(payload, rsaCryptoServiceProvider_MSEnchancedCSP, JwsAlgorithm.RS256);
                    }
                    else
                    {
                        UPSBrowserLogger.LogError(loggingCategory, $"Cannot recreate RsaCryptoServiceProvider with MS Enhanced CSP, the original cert private key is not exportable");
                        token = null;
                    }
                };
            });



            UPSBrowserLogger.LogDebug(loggingCategory, $"token: {token}");
            return(token);
        }
Exemple #30
0
 private void BindUserProfilesGridView()
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "BindUserProfilesGridView invoked");
     UserProfilesGridView.DataSourceID = UserProfiles_datasource_ID;
     UserProfilesGridView.DataBind();
 }