Example #1
0
        /// <summary>
        /// Ensures configuration is valid to proceed
        /// </summary>
        /// <returns></returns>
        public virtual ConfigStatus ValidatePrerequisite()
        {
            Status = ConfigStatus.AllGood;
            if (PersistedObject == null)
            {
                Status |= ConfigStatus.PersistedObjectNotFound;
            }
            if (CurrentTrustedLoginProvider == null)
            {
                CurrentTrustedLoginProvider = LDAPCP.GetSPTrustAssociatedWithCP(LDAPCP._ProviderInternalName);
                if (CurrentTrustedLoginProvider == null)
                {
                    Status |= ConfigStatus.NoSPTrustAssociation;
                }
            }
            if (IdentityClaim == null && Status == ConfigStatus.AllGood)
            {
                IdentityClaim = this.IdentityClaim = PersistedObject.AttributesListProp.Find(x => String.Equals(CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType, x.ClaimType, StringComparison.InvariantCultureIgnoreCase) && !x.CreateAsIdentityClaim);
                if (IdentityClaim == null)
                {
                    Status |= ConfigStatus.NoIdentityClaimType;
                }
            }
            if (PersistedObjectVersion != PersistedObject.Version)
            {
                Status |= ConfigStatus.PersistedObjectStale;
            }

            if (Status != ConfigStatus.AllGood)
            {
                LdapcpLogging.Log(String.Format(MostImportantError), TraceSeverity.High, EventSeverity.Information, LdapcpLogging.Categories.Configuration);
            }
            return(Status);
        }
Example #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.LabelVersion.Text = typeof(ConfigurationRepository).Assembly.GetName().Version.ToString();

            // Get trust currently associated with Auth0, if any
            this.currentTrustedLoginProvider = Utils.GetSPTrustedLoginProviderForClaimsProvider(CustomClaimsProvider.ProviderInternalName);
            if (this.currentTrustedLoginProvider == null)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text = TextErrorNoTrustAssociation;
                this.BtnOK.Enabled          = false;
                return;
            }

            if (!this.IsPostBack)
            {
                try
                {
                    this.PopulateFields();
                }
                catch (Exception ex)
                {
                    this.LabelErrorMessage.Text = ex.Message;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
                LblTitle.Text = String.Format("AzureCP v{0} - <a href=\"https://github.com/Yvand/AzureCP\" target=\"_blank\">GitHub.com/Yvand/AzureCP</a>", fvi.FileVersion);
            }

            // Get trust currently associated with AzureCP, if any
            CurrentTrustedLoginProvider = AzureCP.GetSPTrustAssociatedWithCP(AzureCP._ProviderInternalName);
            if (null == CurrentTrustedLoginProvider)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text     = TextErrorNoTrustAssociation;
                this.BtnOK.Enabled              = this.BtnOKTop.Enabled = this.BtnAddLdapConnection.Enabled = this.BtnTestAzureTenantConnection.Enabled = false;
                this.AllowPersistedObjectUpdate = false;
                return;
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // Get SPPersisted Object and create it if it doesn't exist
                PersistedObject = AzureCPConfig.GetFromConfigDB();
                if (PersistedObject == null)
                {
                    this.Web.AllowUnsafeUpdates = true;
                    PersistedObject             = AzureCPConfig.CreatePersistedObject();
                    this.Web.AllowUnsafeUpdates = false;
                }
            });

            this.IdentityClaim = PersistedObject.AzureADObjects.Find(x => String.Equals(CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType, x.ClaimType, StringComparison.InvariantCultureIgnoreCase) && !x.CreateAsIdentityClaim);
            if (null == this.IdentityClaim)
            {
                // Identity claim type is missing in the attributes list
                this.LabelErrorMessage.Text = String.Format(this.TextErrorNoIdentityClaimType, CurrentTrustedLoginProvider.DisplayName, CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType);
                this.BtnOK.Enabled          = this.BtnOKTop.Enabled = this.BtnAddLdapConnection.Enabled = this.BtnTestAzureTenantConnection.Enabled = false;
                return;
            }

            if (ViewState["PersistedObjectVersion"] == null)
            {
                ViewState.Add("PersistedObjectVersion", PersistedObject.Version);
            }
            if ((long)ViewState["PersistedObjectVersion"] != PersistedObject.Version)
            {
                // PersistedObject changed since last time. Should not allow any update
                this.LabelErrorMessage.Text     = TextErrorPersistedObjectStale;
                this.AllowPersistedObjectUpdate = false;
                return;
            }

            if (!this.IsPostBack)
            {
                PopulateFields();
            }
        }
Example #4
0
        public List <IdentityProvider> getIdentityProviders()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked");
            List <IdentityProvider> identityProvidersToReturn = new List <IdentityProvider>();

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

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

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

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

            return(identityProvidersToReturn);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            SPSecurityTokenServiceManager manager = SPSecurityTokenServiceManager.Local;

            string providerName = (string)listBox1.SelectedItem;

            SPTrustedLoginProvider provider = manager.TrustedLoginProviders[providerName];

            manager.TrustedLoginProviders.Remove(provider.Id);
            manager.Update();
        }
        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();
            });
        }
        private void button4_Click(object sender, EventArgs e)
        {
            SPSecurityTokenServiceManager manager = SPSecurityTokenServiceManager.Local;

            string providerName = (string)listBox1.SelectedItem;

            SPTrustedLoginProvider provider = manager.TrustedLoginProviders[providerName];

            provider.UseWReplyParameter = true;
            provider.ProviderRealm      = "https://spdev0223/_trust/";
            provider.ProviderUri        = new Uri("http://localhost:48924/WingtipSTS/default.aspx");


            provider.Update();

            manager.Update();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get trust currently associated with Auth0, if any
            this.currentTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(CustomClaimsProvider.ProviderInternalName);
            if (this.currentTrustedLoginProvider == null)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text = TextErrorNoTrustAssociation;
                this.BtnOK.Enabled = false;
                return;
            }

            if (!this.IsPostBack)
            {
                this.PopulateFields();
            }
        }
Example #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get trust currently associated with Auth0, if any
            this.currentTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(CustomClaimsProvider.ProviderInternalName);
            if (this.currentTrustedLoginProvider == null)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text = TextErrorNoTrustAssociation;
                this.BtnOK.Enabled          = false;
                return;
            }

            if (!this.IsPostBack)
            {
                this.PopulateFields();
            }
        }
Example #10
0
        private void DoFederatedSignOut()
        {
            string providerName = GetProviderNameFromCookie();
            SPTrustedLoginProvider loginProvider = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                loginProvider = GetLoginProvider(providerName);
            });

            if (loginProvider != null)
            {
                string returnUrl = string.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    "{0}://{1}/_layouts/SignOut.aspx",
                    HttpContext.Current.Request.Url.Scheme,
                    HttpContext.Current.Request.Url.Host);
                HttpCookie signOutExpiredCookie = new HttpCookie(SignOutCookieName, string.Empty);
                signOutExpiredCookie.Expires = new DateTime(1970, 1, 1);
                HttpContext.Current.Response.Cookies.Remove(SignOutCookieName);
                HttpContext.Current.Response.Cookies.Add(signOutExpiredCookie);
                WSFederationAuthenticationModule.FederatedSignOut(loginProvider.ProviderUri, new Uri(returnUrl));
            }
        }
        /// <summary>
        /// Downloads the metadata from the federation service and returns the current primary token signing certificate.
        /// </summary>
        /// <param name="provider"></param>
        /// <returns></returns>
        private X509Certificate2 GetCurrentADFSCertificate(SPTrustedLoginProvider provider)
        {
            // The metadata is a XML document we get from the federation metadata endpoint
            var metadataUrl = String.Format("https://{0}/federationmetadata/2007-06/federationmetadata.xml", provider.ProviderUri.Host);
            var request = WebRequest.Create(metadataUrl);
            WebResponse response = null;

            try
            {
                response = request.GetResponse();
            }
            catch (Exception exc)
            {
                Logger.Unexpected(Logger.CategoryFederationMetadata, "Exception downloading metadata: " + exc.Message);
                return null;
            }

            // Once we have downloaded the XML find the primary token signing cert
            var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            var xmlDocument = new XmlDocument();
            xmlDocument.Load(reader);
            var nsManager = new XmlNamespaceManager(xmlDocument.NameTable);
            nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            nsManager.AddNamespace("fed", "http://docs.oasis-open.org/wsfed/federation/200706");
            nsManager.AddNamespace("x", "urn:oasis:names:tc:SAML:2.0:metadata");
            nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

            var certs = xmlDocument.SelectNodes("/x:EntityDescriptor/x:RoleDescriptor[@xsi:type = 'fed:SecurityTokenServiceType']/x:KeyDescriptor[@use = 'signing']", nsManager);
            Logger.Verbose(Logger.CategoryFederationMetadata, String.Format("Found {0} signing certs", certs.Count));

            var primaryBase64 = xmlDocument.SelectSingleNode("/x:EntityDescriptor/ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate", nsManager).InnerText;
            var primaryCert = new X509Certificate2(Encoding.UTF8.GetBytes(primaryBase64));

            Logger.Medium(Logger.CategoryFederationMetadata, String.Format("Primary signing certificate: {0}", primaryCert.Subject));
            return primaryCert;
        }
        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 void button1_Click(object sender, EventArgs e)
        {
            List <SPTrustedClaimTypeInformation> claimMapping = new List <SPTrustedClaimTypeInformation>();
            List <string> strClaimMapping = new List <string>();

            SPTrustedClaimTypeInformation idClaim    = new SPTrustedClaimTypeInformation("EmailAddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
            SPTrustedClaimTypeInformation titleClaim = new SPTrustedClaimTypeInformation("Title", "http://schemas.wingtip.com/sharepoint/2009/08/claims/title", "http://schemas.wingtip.com/sharepoint/2009/08/claims/title");

            titleClaim.AcceptOnlyKnownClaimValues = true;

            idClaim.AddKnownClaimValue("*****@*****.**");
            idClaim.AddKnownClaimValue("*****@*****.**");
            idClaim.AddKnownClaimValue("*****@*****.**");

            titleClaim.AddKnownClaimValue("Engineer");
            titleClaim.AddKnownClaimValue("Manager");
            titleClaim.AddKnownClaimValue("CEO");

            //creating the string[] for all claims, this is required for the construction of SPTrustedLoginProvider
            strClaimMapping.Add(idClaim.InputClaimType);
            strClaimMapping.Add(titleClaim.InputClaimType);


            X509Certificate2 ImportTrustCertificate = new X509Certificate2(@"C:\StudentFiles\LabFiles\Module_6\Resources\STSTestCertPub.cer");

            claimMapping.Add(idClaim);
            claimMapping.Add(titleClaim);

            SPSecurityTokenServiceManager manager  = SPSecurityTokenServiceManager.Local;
            SPTrustedLoginProvider        provider = new SPTrustedLoginProvider(
                manager,
                "WingtipSTS",
                "WingtipSTS",
                new Uri("http://localhost:48924/WingtipSTS/default.aspx"),
                "https://spdev0223/_trust/",
                strClaimMapping.ToArray(),
                idClaim);



            foreach (SPTrustedClaimTypeInformation claimTypeInfo in claimMapping)
            {
                if (claimTypeInfo.InputClaimType == provider.IdentityClaimTypeInformation.InputClaimType)
                {
                    continue;
                }
                provider.AddClaimTypeInformation(claimTypeInfo);
            }

            if (ImportTrustCertificate != null)
            {
                provider.SigningCertificate = ImportTrustCertificate;
            }


            //provider.ClaimProviderName = "ContosoCRMClaimProvider";

            provider.UseWReplyParameter = true;

            manager.TrustedLoginProviders.Add(provider);
            manager.Update();
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
                LblTitle.Text = String.Format("AzureCP v{0} - <a href=\"https://github.com/Yvand/AzureCP\" target=\"_blank\">GitHub.com/Yvand/AzureCP</a>", fvi.FileVersion);
            }

            // Get trust currently associated with AzureCP, if any
            CurrentTrustedLoginProvider = AzureCP.GetSPTrustAssociatedWithCP(AzureCP._ProviderInternalName);
            if (null == CurrentTrustedLoginProvider)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text = TextErrorNoTrustAssociation;
                this.BtnOK.Enabled = this.BtnOKTop.Enabled = this.BtnAddLdapConnection.Enabled = this.BtnTestAzureTenantConnection.Enabled = false;
                this.AllowPersistedObjectUpdate = false;
                return;
            }

            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                // Get SPPersisted Object and create it if it doesn't exist
                PersistedObject = AzureCPConfig.GetFromConfigDB();
                if (PersistedObject == null)
                {
                    this.Web.AllowUnsafeUpdates = true;
                    PersistedObject = AzureCPConfig.CreatePersistedObject();
                    this.Web.AllowUnsafeUpdates = false;
                }
            });

            this.IdentityClaim = PersistedObject.AzureADObjects.Find(x => String.Equals(CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType, x.ClaimType, StringComparison.InvariantCultureIgnoreCase) && !x.CreateAsIdentityClaim);
            if (null == this.IdentityClaim)
            {
                // Identity claim type is missing in the attributes list
                this.LabelErrorMessage.Text = String.Format(this.TextErrorNoIdentityClaimType, CurrentTrustedLoginProvider.DisplayName, CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType);
                this.BtnOK.Enabled = this.BtnOKTop.Enabled = this.BtnAddLdapConnection.Enabled = this.BtnTestAzureTenantConnection.Enabled = false;
                return;
            }

            if (ViewState["PersistedObjectVersion"] == null)
                ViewState.Add("PersistedObjectVersion", PersistedObject.Version);
            if ((long)ViewState["PersistedObjectVersion"] != PersistedObject.Version)
            {
                // PersistedObject changed since last time. Should not allow any update
                this.LabelErrorMessage.Text = TextErrorPersistedObjectStale;
                this.AllowPersistedObjectUpdate = false;
                return;
            }

            if (!this.IsPostBack)
            {
                PopulateFields();
            }
        }
Example #15
0
        /// <summary>
        /// Initializes claim provider. This method is reserved for internal use and is not intended to be called from external code or changed
        /// </summary>
        public bool Initialize(Uri context, string[] entityTypes)
        {
            // Ensures thread safety to initialize class variables
            lock (Sync_Init)
            {
                // 1ST PART: GET CONFIGURATION OBJECT
                AzureCPConfig globalConfiguration = null;
                bool refreshConfig = false;
                bool success = true;
                bool initializeFromPersistedObject = true;
                try
                {
                    if (SPTrust == null)
                    {
                        SPTrust = GetSPTrustAssociatedWithCP(ProviderInternalName);
                        if (SPTrust == null) return false;
                    }
                    if (!CheckIfShouldProcessInput(context)) return false;

                    // Should not try to get PersistedObject if not OOB AzureCP since with current design it works correctly only for OOB AzureCP
                    if (String.Equals(ProviderInternalName, AzureCP._ProviderInternalName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        globalConfiguration = AzureCPConfig.GetFromConfigDB();
                        if (globalConfiguration == null)
                        {
                            AzureCPLogging.Log(String.Format("[{0}] AzureCPConfig PersistedObject not found. Visit AzureCP admin pages in central administration to create it.", ProviderInternalName),
                                TraceSeverity.Unexpected, EventSeverity.Error, AzureCPLogging.Categories.Core);
                            // Cannot continue since it's not inherited and no persisted object exists
                            success = false;
                        }
                        else if (globalConfiguration.AzureADObjects == null || globalConfiguration.AzureADObjects.Count == 0)
                        {
                            AzureCPLogging.Log(String.Format("[{0}] AzureCPConfig PersistedObject was found but there are no AzureADObject set. Visit AzureCP admin pages in central administration to create it.", ProviderInternalName),
                                TraceSeverity.Unexpected, EventSeverity.Error, AzureCPLogging.Categories.Core);
                            // Cannot continue
                            success = false;
                        }
                        else if (globalConfiguration.AzureTenants == null || globalConfiguration.AzureTenants.Count == 0)
                        {
                            AzureCPLogging.Log(String.Format("[{0}] AzureCPConfig PersistedObject was found but there are no Azure tenant set. Visit AzureCP admin pages in central administration to add one.", ProviderInternalName),
                                TraceSeverity.Unexpected, EventSeverity.Error, AzureCPLogging.Categories.Core);
                            // Cannot continue
                            success = false;
                        }
                        else
                        {
                            // Persisted object is found and seems valid
                            AzureCPLogging.Log(String.Format("[{0}] AzureCPConfig PersistedObject found, version: {1}, previous version: {2}", ProviderInternalName, globalConfiguration.Version.ToString(), this.AzureCPConfigVersion.ToString()),
                                TraceSeverity.Verbose, EventSeverity.Information, AzureCPLogging.Categories.Core);
                            if (this.AzureCPConfigVersion != globalConfiguration.Version)
                            {
                                refreshConfig = true;
                                this.AzureCPConfigVersion = globalConfiguration.Version;
                                AzureCPLogging.Log(String.Format("[{0}] AzureCPConfig PersistedObject changed, refreshing configuration", ProviderInternalName),
                                    TraceSeverity.Medium, EventSeverity.Information, AzureCPLogging.Categories.Core);
                            }
                        }
                    }
                    else
                    {
                        // AzureCP class inherited, refresh config
                        // Configuration will be retrieved in SetCustomSettings method
                        initializeFromPersistedObject = false;
                        refreshConfig = true;
                        AzureCPLogging.Log(String.Format("[{0}] AzureCP class inherited", ProviderInternalName),
                            TraceSeverity.Verbose, EventSeverity.Information, AzureCPLogging.Categories.Core);
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    AzureCPLogging.LogException(ProviderInternalName, "in Initialize", AzureCPLogging.Categories.Core, ex);
                }
                finally
                { }

                if (!success) return success;
                if (!refreshConfig) return success;

                // 2ND PART: APPLY CONFIGURATION
                // Configuration needs to be refreshed, lock current thread in write mode
                Lock_Config.EnterWriteLock();
                try
                {
                    AzureCPLogging.Log(String.Format("[{0}] Refreshing configuration", ProviderInternalName),
                        TraceSeverity.Verbose, EventSeverity.Information, AzureCPLogging.Categories.Core);

                    // Create local persisted object that will never be saved in config DB, it's just a local copy
                    this.CurrentConfiguration = new AzureCPConfig();
                    if (initializeFromPersistedObject)
                    {
                        // All settings come from persisted object
                        this.CurrentConfiguration.AlwaysResolveUserInput = globalConfiguration.AlwaysResolveUserInput;
                        this.CurrentConfiguration.FilterExactMatchOnly = globalConfiguration.FilterExactMatchOnly;
                        this.CurrentConfiguration.AugmentAADRoles = globalConfiguration.AugmentAADRoles;

                        // Retrieve AzureADObjects
                        // A copy of collection AzureADObjects must be created because SetActualAADObjectCollection() may change it and it should be made in a copy totally independant from the persisted object
                        this.CurrentConfiguration.AzureADObjects = new List<AzureADObject>();
                        foreach (AzureADObject currentObject in globalConfiguration.AzureADObjects)
                        {
                            // Create a new AzureADObject
                            this.CurrentConfiguration.AzureADObjects.Add(currentObject.CopyPersistedProperties());
                        }

                        // Retrieve AzureTenants
                        // Create a copy of the collection to work in an copy separated from persisted object
                        this.CurrentConfiguration.AzureTenants = new List<AzureTenant>();
                        foreach (AzureTenant currentObject in globalConfiguration.AzureTenants)
                        {
                            // Create a copy from persisted object
                            this.CurrentConfiguration.AzureTenants.Add(currentObject.CopyPersistedProperties());
                        }
                    }
                    else
                    {
                        // All settings come from overriden SetCustomConfiguration method
                        SetCustomConfiguration(context, entityTypes);

                        // Ensure we get what we expect
                        if (this.CurrentConfiguration.AzureADObjects == null || this.CurrentConfiguration.AzureADObjects.Count == 0)
                        {
                            AzureCPLogging.Log(String.Format("[{0}] AzureADObjects was not set. Override method SetCustomConfiguration to set it.", ProviderInternalName), TraceSeverity.Unexpected, EventSeverity.Error, AzureCPLogging.Categories.Core);
                            return false;
                        }

                        if (this.CurrentConfiguration.AzureTenants == null || this.CurrentConfiguration.AzureTenants.Count == 0)
                        {
                            AzureCPLogging.Log(String.Format("[{0}] AzureTenants was not set. Override method SetCustomConfiguration to set it.", ProviderInternalName), TraceSeverity.Unexpected, EventSeverity.Error, AzureCPLogging.Categories.Core);
                            return false;
                        }
                    }
                    success = this.ProcessAzureADObjectCollection(this.CurrentConfiguration.AzureADObjects);
                }
                catch (Exception ex)
                {
                    success = false;
                    AzureCPLogging.LogException(ProviderInternalName, "in Initialize, while refreshing configuration", AzureCPLogging.Categories.Core, ex);
                }
                finally
                {
                    Lock_Config.ExitWriteLock();
                }
                return success;
            }
        }
Example #16
0
 public UPSClaimProvider(string displayName) : base(displayName)
 {
     usersDAL = new UPSUsersDAL();
     SPTrust  = GetSPTrustAssociatedWithCP(ProviderInternalName);
 }
        private void ProcessTrustedProvider(ChosenTrustedProvider ctp, SPTrustedLoginProvider provider)
        {
            Logger.Medium(Logger.CategoryGeneral, "Begin processing trusted provider " + provider.Name);
            ctp.LastLog = new List<string>();
            ctp.Success = false;

            // Get current ADFS certificate
            var adfsCertificate = GetCurrentADFSCertificate(provider);
            if (adfsCertificate == null)
            {
                Logger.Unexpected(Logger.CategoryFederationMetadata, "Didn't get any token signing certificate. Skipping this provider");
                ctp.LastLog.Add("Didn't get any token signing certificate from federation metadata.");
                return;
            }
            // Check if the certificate has changed
            if (adfsCertificate.Thumbprint.Equals(provider.SigningCertificate.Thumbprint))
            {
                Logger.Medium(Logger.CategoryProviderCertificate, "The signing certificate has not changed. Skipping this provider");
                ctp.LastLog.Add("The signing certificate has not changed.");
                return;
            }
            Logger.Medium(Logger.CategoryGeneral, "The primary certificate has changed");
            ctp.LastLog.Add("New primary certificate found: " + adfsCertificate.Subject);
            // Add the certificate of the trusted store
            bool added = AddCertificateToTrust(adfsCertificate);
            // Change the certficate in the provider
            if (added)
            {
                ctp.LastLog.Add("Added the certificate as a trusted authority (or it was already).");
                bool updated = UpdateProviderCertificate(provider, adfsCertificate);
                if (updated)
                {
                    ctp.LastLog.Add("Updated the signing certificate in the provider.");
                }
            }
            ctp.Success = true;
            Logger.Medium(Logger.CategoryGeneral, "Finished processing trusted provider " + provider.Name);
        }
 /// <summary>
 /// Change the token signing certificate in the trusted identity provider.
 /// </summary>
 /// <param name="provider"></param>
 /// <param name="adfsCertificate"></param>
 /// <returns></returns>
 private bool UpdateProviderCertificate(SPTrustedLoginProvider provider, X509Certificate2 adfsCertificate)
 {
     try
     {
         provider.SigningCertificate = adfsCertificate;
         provider.Update();
         Logger.Medium(
             Logger.CategoryProviderCertificate,
             String.Format("Configured the token signing certificate to {0}", adfsCertificate.Subject));
         return true;
     }
     catch (Exception exc)
     {
         Logger.Unexpected(Logger.CategoryProviderCertificate, "Error changing the signing certificate: " + exc.Message);
     }
     return false;
 }
Example #19
0
        /// <summary>
        /// Get SP Trusted Login Provider.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected virtual bool SetLoginProviderForCurrentContext(Uri context)
        {
            var webApplication = SPWebApplication.Lookup(context);

            if (webApplication == null)
            {
                ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), "WebApplication is null.");
                return(false);
            }

            SPSite site = null;

            try
            {
                site = new SPSite(context.AbsoluteUri);
            }
            catch (Exception ex)
            {
                ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), "Error loading site: " + ex.Message);

                this.associatedLoginProvider = Utils.GetSPTrustedLoginProviderForClaimsProvider(ProviderInternalName);
                if (this.associatedLoginProvider != null && this.associatedLoginProvider.IdentityClaimTypeInformation != null)
                {
                    this.identifierClaimType = this.associatedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                }

                if (this.associatedLoginProvider == null)
                {
                    ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), "Associated login provider is null");
                }

                return(this.associatedLoginProvider != null);
            }

            if (site == null)
            {
                ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), "Site is null.");
                return(false);
            }

            using (site)
            {
                var iisSettings = webApplication.GetIisSettingsWithFallback(site.Zone);
                if (!iisSettings.UseTrustedClaimsAuthenticationProvider)
                {
                    ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), site.Zone + " is not enabled with UseTrustedClaimsAuthenticationProvider");
                    return(false);
                }

                // Figure out if we have a trusted login provider.
                foreach (var provider in iisSettings.ClaimsAuthenticationProviders)
                {
                    if (provider.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
                    {
                        if (provider.ClaimProviderName == ProviderInternalName)
                        {
                            this.associatedLoginProvider = Utils.GetSPTrustedLoginProviderForClaimsProvider(ProviderInternalName);
                            if (this.associatedLoginProvider != null && this.associatedLoginProvider.IdentityClaimTypeInformation != null)
                            {
                                this.identifierClaimType = this.associatedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                            }

                            return(this.associatedLoginProvider != null);
                        }
                    }
                }

                if (this.associatedLoginProvider == null)
                {
                    ClaimsProviderEventSource.Log.SetLoginProviderForCurrentContextFailed(context.ToString(), "Associated login provider not found for zone.");
                }

                return(false);
            }
        }
        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;
        }
Example #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get trust currently associated with AzureCP, if any
            CurrentTrustedLoginProvider = AzureCP.GetSPTrustAssociatedWithCP(AzureCP._ProviderInternalName);
            if (null == CurrentTrustedLoginProvider)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text   = TextErrorNoTrustAssociation;
                this.HideAllContent           = true;
                this.BtnCreateNewItem.Visible = false;
                return;
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // Get SPPersisted Object and create it if it doesn't exist
                PersistedObject = AzureCPConfig.GetFromConfigDB();
                if (PersistedObject == null)
                {
                    this.Web.AllowUnsafeUpdates = true;
                    PersistedObject             = AzureCPConfig.CreatePersistedObject();
                    this.Web.AllowUnsafeUpdates = false;
                }
            });

            if (ViewState["PersistedObjectVersion"] == null)
            {
                ViewState.Add("PersistedObjectVersion", PersistedObject.Version);
            }
            if ((long)ViewState["PersistedObjectVersion"] != PersistedObject.Version)
            {
                // PersistedObject changed since last time. Should not allow any update
                this.LabelErrorMessage.Text     = TextErrorPersistedObjectStale;
                this.AllowPersistedObjectUpdate = false;
                return;
            }
            TrustName = CurrentTrustedLoginProvider.Name;

            if (!this.IsPostBack)
            {
                New_DdlPermissionMetadata.Items.Add(String.Empty);
                foreach (object field in typeof(PeopleEditorEntityDataKeys).GetFields())
                {
                    New_DdlPermissionMetadata.Items.Add(((System.Reflection.FieldInfo)field).Name);
                }

                New_DdlGraphProperty.Items.Add(String.Empty);
                New_DdlGraphPropertyToDisplay.Items.Add(String.Empty);
                foreach (object field in typeof(GraphProperty).GetFields())
                {
                    string prop = ((System.Reflection.FieldInfo)field).Name;
                    if (AzureCP.GetGraphPropertyValue(new User(), prop) == null)
                    {
                        continue;
                    }
                    //if (AzureCP.GetGraphPropertyValue(new Group(), prop) == null) continue;
                    //if (AzureCP.GetGraphPropertyValue(new Role(), prop) == null) continue;

                    New_DdlGraphProperty.Items.Add(prop);
                    New_DdlGraphPropertyToDisplay.Items.Add(prop);
                }
            }

            BuildAttributesListTable(this.IsPostBack);
        }
Example #22
0
        /// <summary>
        /// Ensures configuration is valid to proceed
        /// </summary>
        /// <returns></returns>
        public virtual ConfigStatus ValidatePrerequisite()
        {
            if (!this.IsPostBack)
            {
                // DataBind() must be called to bind attributes that are set as "<%# #>"in .aspx
                // But only during initial page load, otherwise it would reset bindings in other controls like SPGridView
                DataBind();
                ViewState.Add("ClaimsProviderName", ClaimsProviderName);
                ViewState.Add("PersistedObjectName", PersistedObjectName);
                ViewState.Add("PersistedObjectID", PersistedObjectID);
            }
            else
            {
                ClaimsProviderName  = ViewState["ClaimsProviderName"].ToString();
                PersistedObjectName = ViewState["PersistedObjectName"].ToString();
                PersistedObjectID   = ViewState["PersistedObjectID"].ToString();
            }

            Status = ConfigStatus.AllGood;
            if (String.IsNullOrEmpty(ClaimsProviderName))
            {
                Status |= ConfigStatus.ClaimsProviderNamePropNotSet;
            }
            if (String.IsNullOrEmpty(PersistedObjectName))
            {
                Status |= ConfigStatus.PersistedObjectNamePropNotSet;
            }
            if (String.IsNullOrEmpty(PersistedObjectID))
            {
                Status |= ConfigStatus.PersistedObjectIDPropNotSet;
            }
            if (Status != ConfigStatus.AllGood)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] {MostImportantError}", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Configuration);
                // Should not go further if those requirements are not met
                return(Status);
            }

            if (CurrentTrustedLoginProvider == null)
            {
                CurrentTrustedLoginProvider = AzureCP.GetSPTrustAssociatedWithCP(this.ClaimsProviderName);
                if (CurrentTrustedLoginProvider == null)
                {
                    Status |= ConfigStatus.NoSPTrustAssociation;
                    return(Status);
                }
            }

            if (PersistedObject == null)
            {
                Status |= ConfigStatus.PersistedObjectNotFound;
            }

            if (Status != ConfigStatus.AllGood)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] {MostImportantError}", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Configuration);
                // Should not go further if those requirements are not met
                return(Status);
            }

            // AzureCPConfig.GetConfiguration will call method AzureCPConfig.CheckAndCleanConfiguration();
            //PersistedObject.CheckAndCleanConfiguration(CurrentTrustedLoginProvider.Name);
            PersistedObject.ClaimTypes.SPTrust = CurrentTrustedLoginProvider;
            if (IdentityCTConfig == null && Status == ConfigStatus.AllGood)
            {
                IdentityCTConfig = PersistedObject.ClaimTypes.FirstOrDefault(x => String.Equals(CurrentTrustedLoginProvider.IdentityClaimTypeInformation.MappedClaimType, x.ClaimType, StringComparison.InvariantCultureIgnoreCase) && !x.UseMainClaimTypeOfDirectoryObject) as IdentityClaimTypeConfig;
                if (IdentityCTConfig == null)
                {
                    Status |= ConfigStatus.NoIdentityClaimType;
                }
            }
            if (PersistedObjectVersion != PersistedObject.Version)
            {
                Status |= ConfigStatus.PersistedObjectStale;
            }

            if (Status != ConfigStatus.AllGood)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] {MostImportantError}", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Configuration);
            }
            return(Status);
        }
Example #23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get trust currently associated with AzureCP, if any
            CurrentTrustedLoginProvider = AzureCP.GetSPTrustAssociatedWithCP(AzureCP._ProviderInternalName);
            if (null == CurrentTrustedLoginProvider)
            {
                // Claim provider is currently not associated with any trust.
                // Display a message in the page and disable controls
                this.LabelErrorMessage.Text = TextErrorNoTrustAssociation;
                this.HideAllContent = true;
                this.BtnCreateNewItem.Visible = false;
                return;
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // Get SPPersisted Object and create it if it doesn't exist
                PersistedObject = AzureCPConfig.GetFromConfigDB();
                if (PersistedObject == null)
                {
                    this.Web.AllowUnsafeUpdates = true;
                    PersistedObject = AzureCPConfig.CreatePersistedObject();
                    this.Web.AllowUnsafeUpdates = false;
                }
            });

            if (ViewState["PersistedObjectVersion"] == null)
                ViewState.Add("PersistedObjectVersion", PersistedObject.Version);
            if ((long)ViewState["PersistedObjectVersion"] != PersistedObject.Version)
            {
                // PersistedObject changed since last time. Should not allow any update
                this.LabelErrorMessage.Text = TextErrorPersistedObjectStale;
                this.AllowPersistedObjectUpdate = false;
                return;
            }
            TrustName = CurrentTrustedLoginProvider.Name;

            if (!this.IsPostBack)
            {
                New_DdlPermissionMetadata.Items.Add(String.Empty);
                foreach (object field in typeof(PeopleEditorEntityDataKeys).GetFields())
                {
                    New_DdlPermissionMetadata.Items.Add(((System.Reflection.FieldInfo)field).Name);
                }

                New_DdlGraphProperty.Items.Add(String.Empty);
                New_DdlGraphPropertyToDisplay.Items.Add(String.Empty);
                foreach (object field in typeof(GraphProperty).GetFields())
                {
                    string prop = ((System.Reflection.FieldInfo)field).Name;
                    if (AzureCP.GetGraphPropertyValue(new User(), prop) == null) continue;
                    //if (AzureCP.GetGraphPropertyValue(new Group(), prop) == null) continue;
                    //if (AzureCP.GetGraphPropertyValue(new Role(), prop) == null) continue;

                    New_DdlGraphProperty.Items.Add(prop);
                    New_DdlGraphPropertyToDisplay.Items.Add(prop);
                }
            }

            BuildAttributesListTable(this.IsPostBack);
        }