示例#1
0
        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();
                }
            }
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;

            //Build MasterXmlFragment if SPListItem is blank or missing attributes
            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb site = siteCollection.OpenWeb())
                {
                    try
                    {
                        SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - StsFarm");
                        if (list != null)
                        {
                            if (list.ItemCount >= 1)
                            {
                                foreach (SPListItem item in list.Items)
                                {
                                    if (item["StsConfig"].ToString() == "MasterXmlFragment")
                                    {
                                        try
                                        {
                                            MasterXmlFragment.LoadXml((string)item["XMLStsConfig"]);
                                        }
                                        catch (XmlException)
                                        {
                                            MasterXmlFragment.AppendChild(
                                                MasterXmlFragment.CreateNode(XmlNodeType.Element, "system.web", ""));
                                        }

                                        if (MasterXmlFragment.SelectSingleNode(@"system.web/membership") == null)
                                        {
                                            CreateStsXPath(MasterXmlFragment, item, "system.web/membership");
                                        }

                                        if (MasterXmlFragment.SelectSingleNode(@"system.web/membership/providers") ==
                                            null)
                                        {
                                            CreateStsXPath(MasterXmlFragment, item, "system.web/membership/providers");
                                        }

                                        if (MasterXmlFragment.SelectSingleNode(@"system.web/roleManager") == null)
                                        {
                                            CreateStsXPath(MasterXmlFragment, item, "system.web/roleManager");
                                        }

                                        if (MasterXmlFragment.SelectSingleNode(@"system.web/roleManager/providers") ==
                                            null)
                                        {
                                            CreateStsXPath(MasterXmlFragment, item, "system.web/roleManager/providers");
                                        }

                                        if (
                                            MasterXmlFragment.SelectSingleNode(
                                                @"system.web/roleManager[@enabled='true']") == null)
                                        {
                                            var roleManagerNode =
                                                (XmlElement)
                                                MasterXmlFragment.SelectSingleNode(@"system.web/roleManager");
                                            roleManagerNode.SetAttribute("enabled", "true");
                                            item["XMLStsConfig"] = MasterXmlFragment.OuterXml;

                                            try
                                            {
                                                item.Update();
                                            }
                                            catch (SPException ex)
                                            {
                                                Logging.LogMessage(950, Logging.LogCategories.STSXML,
                                                                   TraceSeverity.Unexpected,
                                                                   String.Format(
                                                                       "Unable to update the StsFarm List in Central Administration. {0}",
                                                                       ex.StackTrace),
                                                                   new object[] { null });
                                                throw new SPException(
                                                          @"Unable to update the StsFarm List in Central Administration.  Check to see if the item was removed.");
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                SPListItem item = list.Items.Add();
                                item["StsConfig"]    = "MasterXmlFragment";
                                item["XMLStsConfig"] =
                                    @"<system.web><membership><providers /></membership><roleManager enabled='true'><providers /></roleManager></system.web>";

                                try
                                {
                                    item.Update();
                                }
                                catch (SPException ex)
                                {
                                    Logging.LogMessage(950, Logging.LogCategories.STSXML, TraceSeverity.Unexpected,
                                                       String.Format(
                                                           "Unable to update the StsFarm List in Central Administration. {0}",
                                                           ex.StackTrace),
                                                       new object[] { null });
                                    throw new SPException(
                                              @"Unable to update the StsFarm List in Central Administration.  Check to see if the item was removed.");
                                }
                            }
                        }
                    }
                    catch (SPException ex)
                    {
                        Logging.LogMessage(950, Logging.LogCategories.STSXML, TraceSeverity.Unexpected,
                                           String.Format("Unable to update the StsFarm List in Central Administration. {0}",
                                                         ex.StackTrace),
                                           new object[] { null });
                        throw new SPException(@"Unable to update the StsFarm List in Central Administration.  Validate the list exists.");
                    }

                    try
                    {
                        SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - WebApplicationSettings");

                        if (list != null)
                        {
                            SPListItemCollection items = list.Items;

                            foreach (SPListItem item in items)
                            {
                                var zone = GetZone(item);
                                if (item["WebApplicationUrl"].ToString() ==
                                    webApp.GetResponseUri(zone).ToString())
                                {
                                    //Set the Membership and Role providers for the Web Application
                                    var ap = new SPFormsAuthenticationProvider(
                                        item["WebApplicationMembershipProvider"].ToString(), item["WebApplicationRoleProvider"].ToString());

                                    //Set the custom URL
                                    try
                                    {
                                        var customUrl = item["CustomUrl"].ToString();
                                        webApp.IisSettings[zone].ClaimsAuthenticationRedirectionUrl =
                                            new Uri(customUrl, UriKind.RelativeOrAbsolute);
                                    }
                                    catch (NullReferenceException)
                                    {
                                        //CustomUrl is null
                                    }

                                    try
                                    {
                                        webApp.IisSettings[zone].AddClaimsAuthenticationProvider(ap);
                                        webApp.Update();
                                        webApp.ProvisionGlobally();
                                    }
                                    catch (ArgumentException)
                                    {
                                        foreach (
                                            var provider in
                                            webApp.IisSettings[zone].ClaimsAuthenticationProviders)
                                        {
                                            if (provider.ClaimProviderName == "Forms")
                                            {
                                                webApp.IisSettings[zone].DeleteClaimsAuthenticationProvider(provider);
                                                webApp.Update();
                                                break;
                                            }
                                        }
                                        webApp.IisSettings[zone].AddClaimsAuthenticationProvider(ap);
                                        webApp.Update();
                                        webApp.ProvisionGlobally();
                                    }

                                    try
                                    {
                                        WebModifications.CreateWildcardNode(false, webApp, zone);
                                        WebModifications.CreateProviderNode(false, webApp, zone);
                                        WebModifications.CreateStsProviderNode(false, properties, zone);
                                        WebModifications.CreateAdminWildcardNode(false, webApp, zone);
                                        WebModifications.CreateAdminProviderNode(false, webApp, zone);

                                        var local = SPFarm.Local;

                                        var services = from s in local.Services
                                                       where s.Name == "SPTimerV4"
                                                       select s;

                                        var service = services.First();

                                        foreach (SPJobDefinition job in service.JobDefinitions)
                                        {
                                            if (job.Name == tJobName)
                                            {
                                                if (job.IsDisabled)
                                                {
                                                    job.IsDisabled = false;
                                                }
                                                job.Update();
                                                job.RunNow();
                                            }
                                        }
                                    }
                                    catch (SPException ex)
                                    {
                                        Logging.LogMessage(952, Logging.LogCategories.STSXML, TraceSeverity.Unexpected,
                                                           String.Format("An unknown error has occurred. {0}",
                                                                         ex.StackTrace),
                                                           new object[] { null });
                                        throw new SPException(@"An unknown error has occurred. Please review the ULS file.");
                                    }
                                }
                            }
                        }
                    }
                    catch (SPException ex)
                    {
                        Logging.LogMessage(951, Logging.LogCategories.STSXML, TraceSeverity.Unexpected,
                                           String.Format("Unable to update the WebApplicationSettings List in Central Administration. {0}",
                                                         ex.StackTrace),
                                           new object[] { null });
                        throw new SPException(@"Unable to update the WebApplicationSettings List in Central Administration.  Validate the list exists.");
                    }
                }
            }
        }
示例#3
0
        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();
                    }
                }
            }
        }
示例#4
0
        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);
        }