private void EnableAnonumous(SPFeatureReceiverProperties properties) { try { if (webApp != null) { SPUrlZone urlZone = SPUrlZone.Default; //SPWebApplication specifiedWebApplication = specifiedSite.WebApplication; SPIisSettings iisSettings = webApp.IisSettings[urlZone]; iisSettings.AuthenticationMode = AuthenticationMode.Windows; iisSettings.AllowAnonymous = true; try { SPWebConfigModificationExtensions.WaitForOnetimeJobToFinish(webApp.Farm, "job-webconfig-modification", 180); webApp.Farm.Services.GetValue <SPWebService>().ApplyWebConfigModifications(); ////webApp.WebService.ApplyWebConfigModifications(); webApp.Update(); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } }
public static string GetRoleProvider(SPSite site) { // get role provider of whichever zone in the web app is fba enabled SPIisSettings settings = GetFBAIisSettings(site); return(settings.FormsClaimsAuthenticationProvider.RoleProvider); }
/// <summary> /// Extends the web app. /// </summary> /// <param name="webApplication">The web application.</param> /// <param name="description">The description.</param> /// <param name="hostHeader">The host header.</param> /// <param name="port">The port.</param> /// <param name="loadBalancedUrl">The load balanced URL.</param> /// <param name="path">The path.</param> /// <param name="allowAnonymous">if set to <c>true</c> [allow anonymous].</param> /// <param name="useNtlm">if set to <c>true</c> [use NTLM].</param> /// <param name="useSsl">if set to <c>true</c> [use SSL].</param> /// <param name="zone">The zone.</param> public static void ExtendWebApp(SPWebApplication webApplication, string description, string hostHeader, int port, string loadBalancedUrl, string path, bool allowAnonymous, bool useNtlm, bool useSsl, SPUrlZone zone) { SPServerBinding serverBinding = null; SPSecureBinding secureBinding = null; if (!useSsl) { serverBinding = new SPServerBinding(); serverBinding.Port = port; serverBinding.HostHeader = hostHeader; } else { secureBinding = new SPSecureBinding(); secureBinding.Port = port; } SPIisSettings settings = new SPIisSettings(description, allowAnonymous, useNtlm, serverBinding, secureBinding, new DirectoryInfo(path.Trim())); settings.PreferredInstanceId = GetPreferredInstanceId(description); webApplication.IisSettings.Add(zone, settings); webApplication.AlternateUrls.SetResponseUrl(new SPAlternateUrl(new Uri(loadBalancedUrl), zone)); webApplication.AlternateUrls.Update(); webApplication.Update(); webApplication.ProvisionGlobally(); }
protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState) { using (var site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id); } } try { var stringSeparators = new string[] { "-#####-" }; string[] cmds = workItem.TextPayload.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); SPWebApplication webApp = SPWebApplication.Lookup(new Uri(cmds[0])); SPIisSettings iis = webApp.IisSettings[SPUrlZone.Default]; string port; if (iis.ServerBindings.Count > 0) { port = iis.ServerBindings[0].Port.ToString(); } else { string path = iis.Path.ToString(); port = path.Substring(path.LastIndexOf('\\') + 1); } if (!string.IsNullOrEmpty(port)) { port = ":" + port; } var reloadCacheTimerJob = new ReloadCacheTimerJob("Oceanik.ReloadCacheJob" + Guid.NewGuid(), webApp, null, SPJobLockType.None) { Schedule = new SPOneTimeSchedule(DateTime.Now) }; string command = "http://localhost" + port + cmds[1]; reloadCacheTimerJob.Properties.Add("CMD", command); reloadCacheTimerJob.Update(); SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem.ExecuteCommand", command, EventLogEntryType.Information)); } catch (Exception ex) { SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem", ex.Message, EventLogEntryType.Error)); } return(true); }
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); }
private static void Main() { SPSecurity.RunWithElevatedPrivileges(delegate { var farm = SPFarm.Local; var service = farm.Services.GetValue <SPWebService>(""); SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local; Console.WriteLine("list of authentication providers"); foreach (SPWebApplication spWebApplication in service.WebApplications) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("----------------------------------------"); Console.WriteLine("Web Application name : " + spWebApplication.Name); Console.WriteLine(""); foreach (KeyValuePair <SPUrlZone, SPIisSettings> spIisSettingse in spWebApplication.IisSettings) { Console.WriteLine(spIisSettingse.Key + " : " + spWebApplication.IisSettings[spIisSettingse.Key].AuthenticationMode.ToString()); SPIisSettings theSettings = spWebApplication.GetIisSettingsWithFallback(spIisSettingse.Key); //Console.WriteLine("IsTrustedClaimsAuthenticationProvider : " + theSettings.UseTrustedClaimsAuthenticationProvider); if (theSettings.ClaimsAuthenticationProviders != null) //&& theSettings.UseTrustedClaimsAuthenticationProvider { //get the list of authentication providers associated with the zone foreach (SPAuthenticationProvider prov in theSettings.ClaimsAuthenticationProviders) { //get the SPTrustedLoginProvider using the DisplayName SPAuthenticationProvider prov1 = prov; var lp = from SPTrustedLoginProvider spt in sptMgr.TrustedLoginProviders where spt.DisplayName == prov1.DisplayName select spt; //there should only be one match, so retrieve that var loginProviders = lp as SPTrustedLoginProvider[] ?? lp.ToArray(); if ((loginProviders.Any())) { //get the login provider SPTrustedLoginProvider provider = loginProviders.First(); Console.WriteLine("Claims provider name : " + provider.ClaimProviderName); } } } } Console.WriteLine("----------------------------------------"); } Console.ReadLine(); Console.ReadKey(); }); }
public static string GetMembershipProvider(SPSite site) { // get membership provider of whichever zone in the web app is fba enabled SPIisSettings settings = GetFBAIisSettings(site); if (settings == null) { return(null); } return(settings.FormsClaimsAuthenticationProvider.MembershipProvider); }
/// <summary> /// Update the IIS site with the new sitemap entries /// </summary> /// <param name="oSettings">The settings of the IIS application to update</param> private void UpdateIisSite(SPIisSettings oSettings) { string sSiteMapLocation = oSettings.Path + "\\_app_bin\\" + ((_adminSite) ? "admin" : "layouts") + ".sitemap"; XmlDocument oDoc = new XmlDocument(); oDoc.Load(sSiteMapLocation); foreach (string[] arEntry in _entries) { AddNewNode(oDoc, arEntry); } if (_entries.Count > 0) { oDoc.Save(sSiteMapLocation); } }
public static bool IsSamlClaimsBasedEnvironment(SPWeb web) { // Delcare locals bool IsSamlClaimsBased = false; SPIisSettings iis = web.Site.WebApplication.IisSettings[SPUrlZone.Default]; foreach (SPAuthenticationProvider ap in iis.ClaimsAuthenticationProviders) { SPTrustedAuthenticationProvider tap = ap as SPTrustedAuthenticationProvider; if (tap != null) { IsSamlClaimsBased = true; break; } } return(IsSamlClaimsBased); }
protected void lbInternalUsers_Click(object sender, EventArgs e) { try { if (null != SPContext.Current && null != SPContext.Current.Site) { SPIisSettings iisSettings = SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Default]; if (null != iisSettings && iisSettings.UseWindowsClaimsAuthenticationProvider) { SPAuthenticationProvider provider = iisSettings.WindowsClaimsAuthenticationProvider; Redirect(provider); } } } catch (Exception ex) { } }
/// <summary> /// Gets the SAML user name prefix. /// </summary> /// <param name="currentWeb">The current web.</param> /// <returns>User Name Prefix</returns> private string GetSamlUserNamePrefix(SPWeb currentWeb) { // Delcare local string originalIssuer = string.Empty; SPIisSettings iis = currentWeb.Site.WebApplication.IisSettings[SPUrlZone.Default]; string userNamePrefix = string.Empty; foreach (SPAuthenticationProvider ap in iis.ClaimsAuthenticationProviders) { SPTrustedAuthenticationProvider tap = ap as SPTrustedAuthenticationProvider; if (tap != null) { userNamePrefix = string.Format("i:0e.t|{0}|", tap.LoginProviderName); break; } } // Return value return(userNamePrefix); }
private static SPIisSettings GetFBAIisSettings(SPSite site) { SPIisSettings settings = null; // try and get FBA IIS settings from current site zone try { settings = site.WebApplication.IisSettings[site.Zone]; if (settings.UseFormsClaimsAuthenticationProvider) { return(settings); } } catch { // expecting errors here so do nothing } // check each zone type for an FBA enabled IIS site foreach (SPUrlZone zone in Enum.GetValues(typeof(SPUrlZone))) { try { settings = site.WebApplication.IisSettings[(SPUrlZone)zone]; if (settings.UseFormsClaimsAuthenticationProvider) { return(settings); } } catch { // expecting errors here so do nothing } } // return null if FBA not enabled return(null); }
private ClaimsContext(SPContext context) { SPWebApplication webApplication = context.Site.WebApplication; foreach (SPAlternateUrl mapping in webApplication.AlternateUrls) { SPIisSettings settings = webApplication.GetIisSettingsWithFallback(mapping.UrlZone); if (settings.UseFormsClaimsAuthenticationProvider) { this.FormsMembershipProvider = Membership.Providers[settings.FormsClaimsAuthenticationProvider.MembershipProvider]; this.FormsRoleProvider = Roles.Providers[settings.FormsClaimsAuthenticationProvider.RoleProvider]; break; } } SPUser currentUser = context.Web.CurrentUser; if (currentUser != null && SPClaimProviderManager.IsEncodedClaim(currentUser.LoginName)) { SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(currentUser.LoginName); this.IsWindowsUser = claim.OriginalIssuer == "Windows"; if (claim.OriginalIssuer.StartsWith("Forms:")) { if (this.FormsMembershipProvider != null && this.FormsMembershipProvider.Name.Equals(claim.OriginalIssuer.Substring(6), StringComparison.OrdinalIgnoreCase)) { this.FormsUser = this.FormsMembershipProvider.GetUser(claim.Value, false); if (this.FormsUser != null) { this.IsFormsUser = true; this.FormsUserId = claim.Value; this.FormsUserProfile = ProfileBase.Create(this.FormsUser.UserName); } } } } this.IsAnonymous = !this.IsFormsUser && !this.IsWindowsUser; }
protected void Page_Load(object sender, EventArgs e) { SPWeb web = SPContext.Current.Web; var group = web.SiteGroups; if (!IsPostBack) { var companyName = "Trang quản trị"; //HttpContext.GetGlobalResourceObject("napas.resource", "CompanyName").ToString(); SetPageTitles(companyName); if (web.CurrentUser == null) { SPIisSettings iisSettings = SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Default]; if (null != iisSettings && iisSettings.UseWindowsClaimsAuthenticationProvider) { SPAuthenticationProvider provider = iisSettings.WindowsClaimsAuthenticationProvider; RedirectToLoginPage(provider); } } } }
public static void Delete(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone) { SPSite site = null; try { site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri); SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone); foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders) { if (provider is SPFormsAuthenticationProvider) { SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider; SPServiceContext serviceContext = SPServiceContext.GetContext(site); UserProfileManager uPM = new UserProfileManager(serviceContext); SPSecurity.RunWithElevatedPrivileges(delegate() { string search = ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|"; List <UserProfile> uPAResults = uPM.Search(search).Cast <UserProfile>().ToList(); List <SearchResult> usersList = users.Cast <SearchResult>().ToList(); var query = usersList.Select(sr => sr.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString()); HashSet <string> paths = new HashSet <string>(query); var profiles = uPAResults.Select(profile => new { ShouldKeep = paths.Contains(profile[PropertyConstants.DistinguishedName].Value.ToString()), Profile = profile }); foreach (var profile in profiles.Where(result => !result.ShouldKeep)) { try { uPM.RemoveProfile(profile.Profile); Logging.LogMessage(212, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Removed profile " + profile.Profile[PropertyConstants.DistinguishedName].Value, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to delete profile " + profile.Profile[PropertyConstants.DistinguishedName].Value + " " + ex.Message, new object[] { null }); } } }); } } } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null }); } finally { if (site != null) { site.Dispose(); } } }
public static void Create(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone) { foreach (SearchResult user in users) { DirectoryEntry de2 = user.GetDirectoryEntry(); SPSite site = null; try { site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri); SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone); foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders) { if (provider is SPFormsAuthenticationProvider) { SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider; SPServiceContext serviceContext = SPServiceContext.GetContext(site); UserProfileManager uPM = new UserProfileManager(serviceContext); SPSecurity.RunWithElevatedPrivileges(delegate() { if (de2.Properties[loginAttribute].Value != null) { if (!uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString())) { Department = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty : de2.Properties[DepartmentAttrib].Value.ToString(); DistinguishedName = de2.Properties[DistinguishedNameAttrib].Value.ToString(); FirstName = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty : de2.Properties[FirstNameAttrib].Value.ToString(); LastName = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty : de2.Properties[LastNameAttrib].Value.ToString(); Office = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty : de2.Properties[OfficeAttrib].Value.ToString(); PreferredName = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty : de2.Properties[PreferredNameAttrib].Value.ToString(); UserTitle = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty : de2.Properties[UserTitleAttrib].Value.ToString(); WebSite = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty : de2.Properties[WebSiteAttrib].Value.ToString(); WorkEmail = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty : de2.Properties[WorkEmailAttrib].Value.ToString(); WorkPhone = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty : de2.Properties[WorkPhoneAttrib].Value.ToString(); UserProfile newProfile = uPM.CreateUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString(), PreferredName); newProfile[PropertyConstants.Department].Add(Department); newProfile[PropertyConstants.DistinguishedName].Add(DistinguishedName); newProfile[PropertyConstants.FirstName].Add(FirstName); newProfile[PropertyConstants.LastName].Add(LastName); newProfile[PropertyConstants.Office].Add(Office); newProfile[PropertyConstants.Title].Add(UserTitle); newProfile[PropertyConstants.WebSite].Add(WebSite); newProfile[PropertyConstants.WorkEmail].Add(WorkEmail); newProfile[PropertyConstants.WorkPhone].Add(WorkPhone); try { newProfile.Commit(); Logging.LogMessage(210, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Created profile " + DistinguishedName, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(510, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to create profile " + DistinguishedName + " " + ex.Message, new object[] { null }); } } else if (uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString())) { UserProfile updateProfile = uPM.GetUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" + de2.Properties[loginAttribute].Value.ToString()); updateProfile[PropertyConstants.Department].Value = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty : de2.Properties[DepartmentAttrib].Value.ToString(); updateProfile[PropertyConstants.DistinguishedName].Value = de2.Properties[DistinguishedNameAttrib].Value.ToString(); updateProfile[PropertyConstants.FirstName].Value = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty : de2.Properties[FirstNameAttrib].Value.ToString(); updateProfile[PropertyConstants.LastName].Value = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty : de2.Properties[LastNameAttrib].Value.ToString(); updateProfile[PropertyConstants.Office].Value = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty : de2.Properties[OfficeAttrib].Value.ToString(); updateProfile[PropertyConstants.PreferredName].Value = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty : de2.Properties[PreferredNameAttrib].Value.ToString(); updateProfile[PropertyConstants.Title].Value = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty : de2.Properties[UserTitleAttrib].Value.ToString(); updateProfile[PropertyConstants.WebSite].Value = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty : de2.Properties[WebSiteAttrib].Value.ToString(); updateProfile[PropertyConstants.WorkEmail].Value = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty : de2.Properties[WorkEmailAttrib].Value.ToString(); updateProfile[PropertyConstants.WorkPhone].Value = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty : de2.Properties[WorkPhoneAttrib].Value.ToString(); try { updateProfile.Commit(); Logging.LogMessage(211, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Updated profile " + updateProfile[PropertyConstants.DistinguishedName].Value, new object[] { null }); } catch (Exception ex) { Logging.LogMessage(511, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to update profile " + updateProfile[PropertyConstants.DistinguishedName].Value + " " + ex.Message, new object[] { null }); } } } }); } } } catch (Exception ex) { Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null }); } finally { if (site != null) { site.Dispose(); } } } }
/// <summary> /// Gets the global resources path. /// </summary> /// <param name="oSettings">The o settings.</param> /// <returns>The AppGlobalResourcespath</returns> private static string GetGlobalResourcesPath(SPIisSettings oSettings) { // The settings of the IIS application to update // SPIisSettings oSettings = webApp.IisSettings[zone]; return(Path.Combine(oSettings.Path.ToString(), "App_GlobalResources")); }
/// <summary> /// Update the IIS site with the new sitemap entries /// </summary> /// <param name="oSettings">The settings of the IIS application to update</param> private void UpdateIisSite(SPIisSettings oSettings) { string sSiteMapLocation = oSettings.Path + "\\_app_bin\\" + ((_adminSite) ? "admin" : "layouts") + ".sitemap"; XmlDocument oDoc = new XmlDocument(); oDoc.Load(sSiteMapLocation); foreach (string[] arEntry in _entries) AddNewNode(oDoc, arEntry); if (_entries.Count > 0) oDoc.Save(sSiteMapLocation); }
protected override void OnLoad(EventArgs e) { if (!IsPostBack) { if (SPContext.Current == null) { return; } if (SPContext.Current.Site == null) { return; } if (SPContext.Current.Site.WebApplication == null) { return; } SPWebApplication app = SPContext.Current.Site.WebApplication; SignInConfiguration config = app.GetChild <SignInConfiguration>("SignInConfig"); if (config == null) { throw new NullReferenceException("Config was not found"); } SPAlternateUrl u = app.AlternateUrls[Request.Url]; if (u == null) { throw new NullReferenceException("Could not find " + Request.Url + " in alternate URLs"); } SPUrlZone zone = u.UrlZone; string components = Request.Url.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped); if (!app.IisSettings.ContainsKey(zone)) { zone = SPUrlZone.Default; } //throw new KeyNotFoundException("IIS settings did not have zone " + zone); SPIisSettings settings = app.IisSettings[zone]; bool isMappingFound = false; IPAddress ipv4 = IpNetworking.GetIP4Address(); string targetProvider; try { KeyValuePair <IPNetwork, string> providerMapping = config.ProviderMappings .Select(kvp => new KeyValuePair <IPNetwork, string>(IPNetwork.Parse(kvp.Key), kvp.Value)) .Where(x => IPNetwork.Contains(x.Key, ipv4)) .OrderBy(x => x.Key.Cidr) .Last(); isMappingFound = true; targetProvider = providerMapping.Value; } catch { isMappingFound = false; targetProvider = null; } var signinPageMappings = config.SingInPageMappings; if (config != null && isMappingFound) { foreach (SPAuthenticationProvider provider in settings.ClaimsAuthenticationProviders) { if (string.Compare(provider.DisplayName, targetProvider, true, System.Globalization.CultureInfo.CurrentUICulture) == 0 || string.Compare(provider.ClaimProviderName, targetProvider, true, System.Globalization.CultureInfo.CurrentUICulture) == 0) { string url = provider.AuthenticationRedirectionUrl.ToString(); if (signinPageMappings.ContainsKey(provider.DisplayName)) { url = signinPageMappings[provider.DisplayName]; } if (provider is SPWindowsAuthenticationProvider) { components = EnsureReturnUrl(components); } SPUtility.Redirect(url, SPRedirectFlags.Default, this.Context, components); } } base.OnLoad(e); } else { string loginPage = string.Empty; if (signinPageMappings.ContainsKey("default")) { loginPage = signinPageMappings["default"]; } if (!string.IsNullOrEmpty(loginPage)) { SPUtility.Redirect(loginPage, SPRedirectFlags.Default, this.Context, components); base.OnLoad(e); } } } }
protected virtual SecurityToken GetSecurityToken(Login formsSignInControl) { if (formsSignInControl == null) { throw new ArgumentNullException("formsSignInControl"); } SecurityToken securityToken = null; //AAM settings must correnspond with the domain(s). SPIisSettings iisSettings = this.IisSettings; if (!iisSettings.UseClaimsAuthentication || !iisSettings.UseFormsClaimsAuthenticationProvider) { /* * ULSCat msoulscatWSSClaimsAuthentication = ULSCat.msoulscat_WSS_ClaimsAuthentication; * string str = string.Concat(this.LogPrefix, "Loaded the FormsSignInPage from request '{0}' but we are not in a context where claims forms sign is is enabled."); * object[] contextUri = new object[] { SPAlternateUrl.ContextUri }; * ULS.SendTraceTag(1430947, msoulscatWSSClaimsAuthentication, ULSTraceLevel.Unexpected, str, contextUri); */ throw new InvalidOperationException(); } //Initialize Providers try { ZimbraMembershipProvider z_membershipProvider = (ZimbraMembershipProvider)Membership.Providers["ZimbraMembershipProvider"]; ZimbraRoleProvider z_roleProvider = (ZimbraRoleProvider)Roles.Providers["ZimbraRoleProvider"]; } catch (Exception ex) { ProviderLogging.LogError(ex); } if (this.IsLoginControlInValidState(formsSignInControl)) { //string str1 = null; Uri appliesTo = this.AppliesTo; SPFormsAuthenticationProvider formsClaimsAuthenticationProvider = iisSettings.FormsClaimsAuthenticationProvider; CultureInfo invariantCulture = CultureInfo.InvariantCulture; object[] userName = new object[] { (formsSignInControl.RememberMeSet ? string.Empty : "non-"), formsSignInControl.UserName, formsClaimsAuthenticationProvider.MembershipProvider, formsClaimsAuthenticationProvider.RoleProvider, appliesTo, SPAlternateUrl.ContextUri }; //str1 = string.Format(invariantCulture, "{0}persistant security token for user '{1}' with membership provider '{2}' and role provider '{3}' with applies to '{4}' for request '{5}'.", userName); //ULS.SendTraceTag(1430977, ULSCat.msoulscat_WSS_ClaimsAuthentication, ULSTraceLevel.Verbose, string.Concat(this.LogPrefix, "Requesting a ", str1)); SPFormsAuthenticationOption sPFormsAuthenticationOption = SPFormsAuthenticationOption.None; if (formsSignInControl.RememberMeSet) { sPFormsAuthenticationOption = SPFormsAuthenticationOption.PersistentSignInRequest; } try { securityToken = SPSecurityContext.SecurityTokenForFormsAuthentication(appliesTo, formsClaimsAuthenticationProvider.MembershipProvider, formsClaimsAuthenticationProvider.RoleProvider, formsSignInControl.UserName, formsSignInControl.Password, sPFormsAuthenticationOption); //ULS.SendTraceTag(1430978, ULSCat.msoulscat_WSS_ClaimsAuthentication, ULSTraceLevel.Verbose, string.Concat(this.LogPrefix, "Successfully got a ", str1)); } catch //(Exception exception1) { /* * Exception exception = exception1; * ULSCat uLSCat = ULSCat.msoulscat_WSS_ClaimsAuthentication; * string str2 = string.Concat(this.LogPrefix, "Failed to get a ", str1, " Exception: '{0}'"); * object[] objArray = new object[] { exception }; * ULS.SendTraceTag(1430979, uLSCat, ULSTraceLevel.Verbose, str2, objArray); */ securityToken = null; //SPSecurityContext.SecurityTokenForContext } } else { /* * ULSCat msoulscatWSSClaimsAuthentication1 = ULSCat.msoulscat_WSS_ClaimsAuthentication; * string str3 = string.Concat(this.LogPrefix, "Cancelling sign-in for request '{0}'."); * object[] contextUri1 = new object[] { SPAlternateUrl.ContextUri }; * ULS.SendTraceTag(1430976, msoulscatWSSClaimsAuthentication1, ULSTraceLevel.VerboseEx, str3, contextUri1); */ securityToken = null; } return(securityToken); }
protected virtual bool SetSPTrustInCurrentContext(Uri context) { var webApp = SPWebApplication.Lookup(context); if (webApp == null) { return(false); } SPSite site = null; try { site = new SPSite(context.AbsoluteUri); } catch (Exception) { // The root site doesn't exist this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName); if (this.associatedSPTrustedLoginProvider != null && this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null) { this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType; } return(this.associatedSPTrustedLoginProvider != null); } if (site == null) { return(false); } SPUrlZone currentZone = site.Zone; SPIisSettings iisSettings = webApp.GetIisSettingsWithFallback(currentZone); site.Dispose(); if (!iisSettings.UseTrustedClaimsAuthenticationProvider) { return(false); } // Get the list of authentication providers associated with the zone foreach (SPAuthenticationProvider prov in iisSettings.ClaimsAuthenticationProviders) { if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider)) { // Check if the current SPTrustedAuthenticationProvider is associated with the claim provider if (prov.ClaimProviderName == ProviderInternalName) { this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName); if (this.associatedSPTrustedLoginProvider != null && this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null) { this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType; } return(this.associatedSPTrustedLoginProvider != null); } } } return(false); }
private static void CleanOldHandlers() { var webServices = new SPWebServiceCollection(SPFarm.Local); foreach (SPWebService webService in webServices) { foreach (SPWebApplication webApp in webService.WebApplications) { if (!webApp.IsAdministrationWebApplication) { try { // Get the filepath location for the web.config SPIisSettings settings = webApp.GetIisSettingsWithFallback(SPUrlZone.Default); DirectoryInfo iisPath = settings.Path; string webConfigpath = iisPath.FullName + "\\web.config"; // start reading the web.config in order to add appropriate text var configReader = new StreamReader(webConfigpath); string configContents = configReader.ReadToEnd(); configReader.Close(); string moduleText = "<add name=\"AlphaMosaikTranslation\" type=\"TranslatorHttpHandler.TranslatorModule, TranslatorHttpHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a65beeb1a6acb37a\" />" + Environment.NewLine; if (configContents.IndexOf(moduleText) != -1) { // remove old handler configContents = configContents.Replace(moduleText, string.Empty); var configWriter = new StreamWriter(webConfigpath); configWriter.Write(configContents); configWriter.Flush(); configWriter.Close(); foreach (SPSite site in webApp.Sites) { var list = new List(site.Url, "/", "LanguagesVisibility"); // Remove Old Assembly list.UnlinkEventHandlerToList("CheckDefaultLangEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7b49392f9e06d3f3", "CheckDefaultLangEvent.ItemEvent", "ItemUpdated"); list.UnlinkEventHandlerToList("CreateGUIDEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4a041d2cfd549304", "CreateGUIDEvent.GenerateId", "ItemAdded"); const string OldAssemblyName = "ReloadCacheEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=45fd9f0eaea17ba9"; const string ClassName = "ReloadCacheEvent.CacheEvent"; list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemAdded"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemDeleting"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemUpdated"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemUpdated"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemUpdated"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemDeleting"); list.UnlinkEventHandlerToList(OldAssemblyName, ClassName, "ItemAdded"); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }