private void SetupFormFields() { UPSBrowserLogger.LogDebug(loggingCategory, "SetupFormFields invoked"); if (formMode == formModeEnum.EditForm) { if (!IsPostBack) { User upsUser = upsUsersDAL.getUserByGuid(userGuid); if (upsUser == null) { string errorMessage = $"Error getting user form UPS by guid: {userGuid}"; UPSBrowserLogger.LogError(loggingCategory, errorMessage); throw new Exception(errorMessage); } ; FillTextboxes(upsUser); } } else { WorkEmailTextBox.Enabled = true; WorkEmailTextBox.ReadOnly = false; AccountNameLabel.Visible = false; AccountNameTextBox.Visible = false; UserGuidLabel.Visible = false; UserGuidTextBox.Visible = false; }; }
private void DeleteButton_Click(object sender, EventArgs e) { UPSBrowserLogger.LogDebug(loggingCategory, "DeleteButton_Click invoked"); string userGuid = UserGuidTextBox.Text; if (upsUsersDAL.deleteUserByGuid(userGuid)) { UPSBrowserLogger.LogDebug(loggingCategory, "User deleted successfully"); needParentRefreshing = true; ErrorMessage.Text = ""; ErrorMessage.Visible = false; CloseForm(); } else { UPSBrowserLogger.LogError(loggingCategory, "Error deleting user"); ErrorMessage.Text = "Error deleting user"; ErrorMessage.Visible = true; return; } }
public User updateUser(User updatedUser) { UPSBrowserLogger.LogDebug(loggingCategory, "updateUser invoked"); UPSBrowserLogger.LogDebug(loggingCategory, $"updatedUser.UserGuid: {updatedUser.UserGuid}"); User userToUpdate = _users.SingleOrDefault(user => user.UserGuid == updatedUser.UserGuid); if (userToUpdate == null) { UPSBrowserLogger.LogError(loggingCategory, $"User profile not found"); //UPSBrowserLogger.LogActivity(userToUpdate.Username, UPSBrowserLogger.LogActivityActionEnum.Update, UPSBrowserLogger.LogActivityResultEnum.Error); ActivityLogger.LogActivity(userToUpdate.AccountName, LogActivityActionEnum.Update, LogActivityResultEnum.Error); return(null); } //_users.Where() UPSBrowserLogger.LogError(loggingCategory, $"User profile found, updating properties"); userToUpdate.WorkEmail = updatedUser.WorkEmail; userToUpdate.AccountName = updatedUser.AccountName; userToUpdate.DisplayName = updatedUser.DisplayName; userToUpdate.JobTitle = updatedUser.JobTitle; userToUpdate.Department = updatedUser.Department; // log completed activity //UPSBrowserLogger.LogActivity(userToUpdate.Username, UPSBrowserLogger.LogActivityActionEnum.Update, UPSBrowserLogger.LogActivityResultEnum.Success); ActivityLogger.LogActivity(userToUpdate.AccountName, LogActivityActionEnum.Update, LogActivityResultEnum.Success); return(userToUpdate); }
private string callJsonWebService(string path, bool isPostRequest, string queryParameters, string body) { UPSBrowserLogger.LogDebug(loggingCategory, "WSExternalUsersSource.callJsonWebService invoked"); UPSBrowserLogger.LogDebug(loggingCategory, $"path: {path}"); UPSBrowserLogger.LogDebug(loggingCategory, $"isPostRequest: {isPostRequest}"); UPSBrowserLogger.LogDebug(loggingCategory, $"queryParameters: {queryParameters}"); UPSBrowserLogger.LogDebug(loggingCategory, $"body: {body}"); if (string.IsNullOrEmpty(wsBaseUrl) || (tokenSigningCert == null)) { string message = "Call Init method to set configuration parameters before calling getUsersBySearchString"; UPSBrowserLogger.LogError(loggingCategory, message); return(null); } ; string jsonString = null; try { string wsUrl = $"{wsBaseUrl}/{path}"; wsUrl = string.IsNullOrEmpty(queryParameters) ? $"{wsUrl}": $"{wsUrl}?{queryParameters}"; WebClient webClient = getWebClient(); // Generating jwt token using the cert selected on the "Settings" tab UPSBrowserLogger.LogDebug(loggingCategory, $"TokenSigningCert.subject: {tokenSigningCert.subject}; TokenSigningCert.friendlyName: {tokenSigningCert.friendlyName}"); ITokenHelper tokenHelper = new TokenHelper(); string tokenString = tokenHelper.getTokenString(tokenSigningCert); if (string.IsNullOrEmpty(tokenString)) { string message = "TokenHelper returned null token, external web service call will not be called"; UPSBrowserLogger.LogError(loggingCategory, message); return(null); } webClient.Headers.Add("Authorization", $"Bearer {tokenString}"); webClient.Headers.Add("Content-Type", "application/json; charset=utf-8"); if (isPostRequest) { jsonString = webClient.UploadString(wsUrl, body); } else { jsonString = webClient.DownloadString(wsUrl); } UPSBrowserLogger.LogDebug(loggingCategory, $"jsonString: {jsonString}"); } catch (Exception e) { string message = $"Error getting data from external web service: {e.Message}"; UPSBrowserLogger.LogError(loggingCategory, message); throw e; }; return(jsonString); }
public static Tuple <string, string> EnsureActivitiesList() { string currentSiteUrl = SPContext.Current.Site.Url; Tuple <string, string> result = null; SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite site = new SPSite(currentSiteUrl)) using (SPWeb rootWeb = site.OpenWeb()) { rootWeb.AllowUnsafeUpdates = true; SPList extistingList = rootWeb.Lists.TryGetList(ActivityLoggerListTitle); if (extistingList != null) { result = Tuple.Create(extistingList.ID.ToString(), extistingList.DefaultView.ID.ToString()); return; } SPListCollection lists = rootWeb.Lists; lists.Add(ActivityLoggerListInternalName, "UPSBrowser logged activities", SPListTemplateType.GenericList); SPList list = rootWeb.Lists[ActivityLoggerListInternalName]; list.Title = ActivityLoggerListTitle; list.Fields.Add("RegisteredDate", SPFieldType.DateTime, true); list.Fields.Add("Initiator", SPFieldType.Text, true); list.Fields.Add("User", SPFieldType.Text, true); list.Fields.Add("Action", SPFieldType.Text, true); list.Fields.Add("Result", SPFieldType.Text, true); list.Fields.Add("AdditionalInfo", SPFieldType.Text, false); list.Update(); SPView view = list.DefaultView; view.ViewFields.Add("RegisteredDate"); view.ViewFields.Add("Initiator"); view.ViewFields.Add("User"); view.ViewFields.Add("Action"); view.ViewFields.Add("Result"); view.ViewFields.Add("AdditionalInfo"); view.Update(); rootWeb.AllowUnsafeUpdates = false; result = Tuple.Create(list.ID.ToString(), list.DefaultView.ID.ToString()); }; } catch (Exception e) { UPSBrowserLogger.LogError(loggingCategory, $"Error creating list '{ActivityLoggerListTitle}' in the root web at {currentSiteUrl}. Exception: {e.Message}"); return; }; }); return(result); }
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); }
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); }
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()); }
static void AddActivityToList(string user, LogActivityActionEnum action, LogActivityResultEnum result, string additionalInfo = "") { // Add activity info record to the list stored in the session storage so that it will available for display /* * HttpContext currentContext = HttpContext.Current; * if (currentContext == null) * { * UPSBrowserLogger.LogError(loggingCategory, "Current HttpContext is null"); * return; * }; */ string currentSiteUrl = SPContext.Current.Site.Url; string initiator = SPContext.Current.Web.CurrentUser.LoginName; SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite site = new SPSite(currentSiteUrl)) using (SPWeb rootWeb = site.OpenWeb()) { rootWeb.AllowUnsafeUpdates = true; SPList list = rootWeb.Lists.TryGetList(ActivityLoggerListTitle); if (list == null) { UPSBrowserLogger.LogError(loggingCategory, $"List '{ActivityLoggerListTitle}' not found in the root web at {currentSiteUrl}"); return; } SPListItem item = list.Items.Add(); item["RegisteredDate"] = DateTime.Now; item["Initiator"] = initiator; item["User"] = user; item["Action"] = action.ToString(); item["Result"] = result.ToString(); item["AdditionalInfo"] = additionalInfo; item.Update(); rootWeb.AllowUnsafeUpdates = false; }; } catch (Exception e) { UPSBrowserLogger.LogError(loggingCategory, $"Error adding record to the list list {ActivityLoggerListTitle} in the root web at {currentSiteUrl}. Exception: {e.Message}"); return; }; }); }
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); }
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); }
public List <User> getUsersBySearchString(string searchString) { UPSBrowserLogger.LogDebug(loggingCategory, "getUsersBySearchString invoked"); UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}"); List <User> usersToReturn = new List <User>(); if (searchString.Length < 3) { return(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"); ProfileBase[] searchResults = userProfileManager.Search(searchString); foreach (ProfileBase profile in searchResults) { UserProfile userProfile = (UserProfile)profile; UPSBrowserLogger.LogDebug(loggingCategory, $"Profile found - AccountName: {userProfile.AccountName}, DisplayName: {userProfile.DisplayName}"); User user = UserProfileToUser(userProfile); string outputString = $"Retrieved user properties - Email: {user.WorkEmail}, Username: {user.AccountName}, DisplayName: {user.DisplayName}, Department: {user.Department}, JobTitle: {user.JobTitle}"; UPSBrowserLogger.LogDebug(loggingCategory, outputString); usersToReturn.Add(user); } ; } 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}"); }; UPSBrowserLogger.LogDebug(loggingCategory, $"usersToReturn.Count: {usersToReturn.Count}"); return(usersToReturn); }
private void SaveButton_Click(object sender, EventArgs e) { UPSBrowserLogger.LogDebug(loggingCategory, "SaveButton_Click invoked"); User userInfo = new UPSBrowser.User { UserGuid = UserGuidTextBox.Text, WorkEmail = WorkEmailTextBox.Text, AccountName = AccountNameTextBox.Text, DisplayName = DisplayNameTextBox.Text, FirstName = FirstNameTextBox.Text, LastName = LastNameTextBox.Text, WorkPhone = WorkPhoneTextBox.Text, CellPhone = CellPhoneTextBox.Text, JobTitle = JobTitleTextBox.Text, Department = DepartmentTextBox.Text }; User user; if (formMode == formModeEnum.NewForm) { user = upsUsersDAL.createUser(userInfo, identityProviderName); if (user != null) { UPSBrowserLogger.LogDebug(loggingCategory, "User created successfully"); needParentRefreshing = true; // Now the only allowed action is to close the form and return to the main view upsbrowser_form_savebutton.Visible = false; DeleteButton.Visible = false; ErrorMessage.Text = ""; ErrorMessage.Visible = false; } else { UPSBrowserLogger.LogError(loggingCategory, "Error creating user"); ErrorMessage.Text = "Error creating user"; ErrorMessage.Visible = true; return; } } else { user = upsUsersDAL.updateUser(userInfo); if (user != null) { UPSBrowserLogger.LogDebug(loggingCategory, "User updated successfully"); needParentRefreshing = true; ErrorMessage.Text = ""; ErrorMessage.Visible = false; } else { UPSBrowserLogger.LogError(loggingCategory, "Error updating user"); ErrorMessage.Text = "Error updating user"; ErrorMessage.Visible = true; return; } } FillTextboxes(user); }
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 }
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); }
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); }
public bool deleteUserByGuid(string guid) { UPSBrowserLogger.LogDebug(loggingCategory, "deleteUserByGuid invoked"); UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}"); bool result = false; string accountNameForLogger = guid; 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"); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error); return; //exit delegate block } ; UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}"); accountNameForLogger = userProfile.AccountName; userProfileManager.RemoveUserProfile(new Guid(guid)); string outputString = $"User profile with guid {guid} deleted"; UPSBrowserLogger.LogDebug(loggingCategory, outputString); result = true; } catch (System.Exception e) { UPSBrowserLogger.LogError(loggingCategory, e.Message); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error); } finally { // Restore HttpContext HttpContext.Current = savedHttpContext; }; }); } catch (System.Exception e) { UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}"); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Error); }; if (result) { ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Delete, LogActivityResultEnum.Success); } ; return(result); }
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); }
public User createUser(User newUser, string identityProviderName) { UPSBrowserLogger.LogDebug(loggingCategory, "createUser invoked"); UPSBrowserLogger.LogDebug(loggingCategory, $"newUser.AccountName: {newUser.AccountName}, newUser.WorkEmail: {newUser.WorkEmail}, newUser.DisplayName: {newUser.DisplayName}"); UPSBrowserLogger.LogDebug(loggingCategory, $"identityProviderName: {identityProviderName}"); User userToReturn = null; string accountNameForLogger = newUser.WorkEmail; 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"); string accountName = identityProvidersHelper.getAccountNameForEmail(newUser.WorkEmail, identityProviderName); accountNameForLogger = accountName; UserProfile userProfile = userProfileManager.CreateUserProfile(accountName, newUser.DisplayName); if (userProfile == null) { UPSBrowserLogger.LogError(loggingCategory, $"Failed to create user profile with AccountName {accountName}"); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error); return; //exit delegate block } ; userProfile[PropertyConstants.WorkEmail].Value = newUser.WorkEmail; userProfile[PropertyConstants.FirstName].Value = newUser.FirstName; userProfile[PropertyConstants.LastName].Value = newUser.LastName; userProfile[PropertyConstants.Department].Value = newUser.Department; userProfile[PropertyConstants.JobTitle].Value = newUser.JobTitle; userProfile[PropertyConstants.Title].Value = newUser.JobTitle; // Title is synced from UPS to User Information List! userProfile[PropertyConstants.WorkPhone].Value = newUser.WorkPhone; userProfile[PropertyConstants.CellPhone].Value = newUser.CellPhone; userProfile.Commit(); UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}, userProfile.AccountName: {userProfile[PropertyConstants.UserGuid]}"); userToReturn = UserProfileToUser(userProfile); string outputString = $"Retrieved user properties - Email: {userToReturn.WorkEmail}, AccountName: {userToReturn.AccountName}, DisplayName: {userToReturn.DisplayName}, UserGuid: {userToReturn.UserGuid}, Department: {userToReturn.Department}, JobTitle: {userToReturn.JobTitle}"; UPSBrowserLogger.LogDebug(loggingCategory, outputString); } catch (System.Exception e) { UPSBrowserLogger.LogError(loggingCategory, e.Message); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error); } finally { // Restore HttpContext HttpContext.Current = savedHttpContext; }; }); } catch (System.Exception e) { UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}"); ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Error); }; if (userToReturn != null) { ActivityLogger.LogActivity(accountNameForLogger, LogActivityActionEnum.Create, LogActivityResultEnum.Success); } ; return(userToReturn); }