private static void FederatedAuthentication_FederationConfigurationCreated(object sender, FederationConfigurationCreatedEventArgs e)
            {
                //from appsettings...
                const string allowedAudience = "http://audience1/user/get";
                const string rpRealm         = "http://audience1/";
                const string domain          = "";
                const bool   requireSsl      = false;
                const string issuer          = "http://sts/token/create;
        const string certThumbprint = " mythumbprint ";
        const string authCookieName = " StsAuth ";

        var federationConfiguration = new FederationConfiguration();
                                 federationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(allowedAudience));

        var issuingAuthority = new IssuingAuthority(internalSts);
        issuingAuthority.Thumbprints.Add(certThumbprint);
        issuingAuthority.Issuers.Add(internalSts);
        var issuingAuthorities = new List<IssuingAuthority> {issuingAuthority};

        var validatingIssuerNameRegistry = new ValidatingIssuerNameRegistry {IssuingAuthorities = issuingAuthorities};
        federationConfiguration.IdentityConfiguration.IssuerNameRegistry = validatingIssuerNameRegistry;
        federationConfiguration.IdentityConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;

        var chunkedCookieHandler = new ChunkedCookieHandler {RequireSsl = false, Name = authCookieName, Domain = domain, PersistentSessionLifetime = new TimeSpan(0, 0, 30, 0)};
        federationConfiguration.CookieHandler = chunkedCookieHandler;
        federationConfiguration.WsFederationConfiguration.Issuer = issuer;
        federationConfiguration.WsFederationConfiguration.Realm = rpRealm;
        federationConfiguration.WsFederationConfiguration.RequireHttps = requireSsl;

        e.FederationConfiguration = federationConfiguration;
                  }
        public static void RefreshKeys(string metadataAddress)
        {
            IssuingAuthority ia =
                ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataAddress);

            bool newKeys = false;

            foreach (string thumbp in ia.Thumbprints)
            {
                if (!ContainsKey(thumbp))
                {
                    newKeys = true;
                    break;
                }
            }

            if (newKeys)
            {
                XElement keysRoot =
                    (XElement)(from tt in doc.Descendants("keys") select tt).First();
                keysRoot.RemoveNodes();
                foreach (string thumbp in ia.Thumbprints)
                {
                    XElement node = new XElement("key", new XAttribute("id", thumbp));
                    keysRoot.Add(node);
                }
                doc.Save(filePath);
            }
        }
        public static FederationConfiguration Create(string relyingPartyUrl, string stsUrl, string domain, string certificateThumbprint, string authCookieName, bool requireSsl)
        {
            var federationConfiguration = new FederationConfiguration();
            federationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(relyingPartyUrl));

            var issuingAuthority = new IssuingAuthority(stsUrl);
            issuingAuthority.Thumbprints.Add(certificateThumbprint);
            issuingAuthority.Issuers.Add(stsUrl);
            var issuingAuthorities = new List<IssuingAuthority> { issuingAuthority };

            var validatingIssuerNameRegistry = new ValidatingIssuerNameRegistry { IssuingAuthorities = issuingAuthorities };
            federationConfiguration.IdentityConfiguration.IssuerNameRegistry = validatingIssuerNameRegistry;
            federationConfiguration.IdentityConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;

            var chunkedCookieHandler = new ChunkedCookieHandler
                                       {
                                           RequireSsl = requireSsl,
                                           Name = authCookieName,
                                           Domain = domain,
                                           PersistentSessionLifetime = new TimeSpan(0, 0, 30, 0)
                                       };
            federationConfiguration.CookieHandler = chunkedCookieHandler;
            var issuerOfToken = stsUrl;
            federationConfiguration.WsFederationConfiguration.Issuer = issuerOfToken;
            federationConfiguration.WsFederationConfiguration.Realm = relyingPartyUrl;
            federationConfiguration.WsFederationConfiguration.RequireHttps = requireSsl;

            return federationConfiguration;
        }
        /// <summary>
        /// RefreshKeys
        /// </summary>
        /// <param name="metadataLocation"></param>
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);

            bool newKeys = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys = true;
                    break;
                }
            }

            if (newKeys)
            {
                using (MyCompanyContext context = new MyCompanyContext())
                {
                    context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                    foreach (string thumbprint in issuingAuthority.Thumbprints)
                    {
                        context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey {
                            Id = thumbprint
                        });
                    }
                    context.SaveChanges();
                }
            }
        }
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);

            bool newKeys       = false;
            bool refreshTenant = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys       = true;
                    refreshTenant = true;
                    break;
                }
            }

            foreach (string issuer in issuingAuthority.Issuers)
            {
                if (!ContainsTenant(GetIssuerId(issuer)))
                {
                    refreshTenant = true;
                    break;
                }
            }

            if (newKeys || refreshTenant)
            {
                using (TenantDbContext context = new TenantDbContext())
                {
                    if (newKeys)
                    {
                        context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                        foreach (string thumbprint in issuingAuthority.Thumbprints)
                        {
                            context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey {
                                Id = thumbprint
                            });
                        }
                    }

                    if (refreshTenant)
                    {
                        // Add the default tenant to the registry.
                        // Comment or remove the following code if you do not wish to have the default tenant use the application.
                        foreach (string issuer in issuingAuthority.Issuers)
                        {
                            string issuerId = GetIssuerId(issuer);
                            if (!ContainsTenant(issuerId))
                            {
                                context.Tenants.Add(new Tenant {
                                    Id = issuerId
                                });
                            }
                        }
                    }
                    context.SaveChanges();
                }
            }
        }
示例#6
0
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);


            bool newKeys       = false;
            bool refreshTenant = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys       = true;
                    refreshTenant = true;
                    break;
                }
            }

            foreach (string issuer in issuingAuthority.Issuers)
            {
                if (!ContainsTenant(GetIssuerId(issuer)))
                {
                    refreshTenant = true;
                    break;
                }
            }

            if (newKeys || refreshTenant)
            {
                using (TenantDbContext context = new TenantDbContext())
                {
                    if (newKeys)
                    {
                        context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                        foreach (string thumbprint in issuingAuthority.Thumbprints)
                        {
                            context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey {
                                Id = thumbprint
                            });
                        }
                    }

                    if (refreshTenant)
                    {
                        foreach (string issuer in issuingAuthority.Issuers)
                        {
                            string issuerId = GetIssuerId(issuer);
                            if (!ContainsTenant(issuerId))
                            {
                                context.Tenants.Add(new Tenant {
                                    Id = issuerId
                                });
                            }
                        }
                    }
                    context.SaveChanges();
                }
            }
        }
        private static void RefreshIssuerKeys()
        {
            // http://msdn.microsoft.com/en-us/library/azure/dn641920.aspx
            var configPath      = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Web.config";
            var metadataAddress = ConfigurationManager.AppSettings["ida:FederationMetadataLocation"];

            ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath);
        }
示例#8
0
        protected void RefreshValidationSettings()
        {
            string configPath      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web.config");
            string metadataAddress =
                ConfigurationManager.AppSettings["ida:FederationMetadataLocation"];

            ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath);
        }
示例#9
0
 protected void RefreshValidationSettings()
 {
     if (!RoleEnvironment.IsAvailable)
     {
         string configPath      = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Web.config";
         string metadataAddress = ConfigurationManager.AppSettings["FederationMetadataLocation"];
         ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath);
     }
     // else { // See WebRole.cs file }
 }
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);

            bool newKeys       = false;
            bool refreshTenant = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys       = true;
                    refreshTenant = true;
                    break;
                }
            }

            foreach (string issuer in issuingAuthority.Issuers)
            {
                if (!ContainsTenant(GetIssuerId(issuer)))
                {
                    refreshTenant = true;
                    break;
                }
            }

            if (newKeys || refreshTenant)
            {
                if (newKeys)
                {
                    session.RemoveBatch <IssuingAuthorityKey>(session.GetQueryable <IssuingAuthorityKey>().Select(i => i.Id).ToList());
                    foreach (string thumbprint in issuingAuthority.Thumbprints)
                    {
                        session.Add(new IssuingAuthorityKey {
                            Id = thumbprint
                        });
                    }
                }

                if (refreshTenant)
                {
                    foreach (string issuer in issuingAuthority.Issuers)
                    {
                        string issuerId = GetIssuerId(issuer);
                        if (!ContainsTenant(issuerId))
                        {
                            session.Add(new Tenant {
                                Id = issuerId
                            });
                        }
                    }
                }
            }
        }
示例#11
0
        private static IssuingAuthority GetIssuingAuthority()
        {
            IssuingAuthority issuingAuthority = issuingAuthorityCache[IssuingAuthorityCacheKey] as IssuingAuthority;

            if (issuingAuthority == null)
            {
                issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(MetadataLocation);
                issuingAuthorityCache.Add(IssuingAuthorityCacheKey, issuingAuthority, DateTimeOffset.UtcNow.AddHours(1.0));
            }

            return(issuingAuthority);
        }
示例#12
0
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);

            bool newKeys       = false;
            bool refreshTenant = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys       = true;
                    refreshTenant = true;
                    break;
                }
            }

            foreach (string issuer in issuingAuthority.Issuers)
            {
                if (!ContainsTenant(GetIssuerId(issuer)))
                {
                    refreshTenant = true;
                    break;
                }
            }

            if (!newKeys && !refreshTenant)
            {
                return;
            }
            if (newKeys)
            {
                //IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                IssuingAuthorityKeys.Clear();
                foreach (var thumbprint in issuingAuthority.Thumbprints)
                {
                    IssuingAuthorityKeys.Add(new IssuingAuthorityKey {
                        Id = thumbprint
                    });
                }
            }

            foreach (
                string issuerId in
                issuingAuthority.Issuers.Select(GetIssuerId).Where(issuerId => !ContainsTenant(issuerId)))
            {
                Tenants.Add(new Tenant {
                    Id = issuerId
                });
            }
        }
示例#13
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            // ....

            string configPath      = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Web.config";
            string metadataAddress =
                ConfigurationManager.AppSettings["ida:FederationMetadataLocation"];

            ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath);

            // Make sure we don't use the Webforms view engine in any way.
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
示例#14
0
        public static FederationConfiguration LoadConfigurationSection()
        {
            var allowedAudience     = MortysMixedAuthenticationConfiguration.Settings.ClientApplicationUri;
            var rpRealm             = MortysMixedAuthenticationConfiguration.Settings.ClientApplicationUri;
            var domain              = "";
            var requireSsl          = true;
            var issuer              = MortysMixedAuthenticationConfiguration.Settings.SecurityTokenIssuerUri;
            var certThumbprint      = MortysMixedAuthenticationConfiguration.Settings.TokenSigningSertificateThumbprint;
            var issuingAuthorityUri = MortysMixedAuthenticationConfiguration.Settings.TokenIssuingAuthorityUri;
            var authCookieName      = "FocusFederatedAuth";

            var federationConfiguration = new FederationConfiguration();

            federationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(allowedAudience));

            var issuingAuthority = new IssuingAuthority(issuingAuthorityUri);

            issuingAuthority.Thumbprints.Add(certThumbprint);
            issuingAuthority.Issuers.Add(issuingAuthorityUri);

            var validatingIssuerNameRegistry = new ValidatingIssuerNameRegistry
            {
                IssuingAuthorities = new List <IssuingAuthority> {
                    issuingAuthority
                }
            };

            federationConfiguration.IdentityConfiguration.IssuerNameRegistry        = validatingIssuerNameRegistry;
            federationConfiguration.IdentityConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;

            var chunkedCookieHandler = new ChunkedCookieHandler {
                RequireSsl = false, Name = authCookieName, Domain = domain, PersistentSessionLifetime = new TimeSpan(0, 0, 30, 0)
            };

            federationConfiguration.CookieHandler = chunkedCookieHandler;

            federationConfiguration.WsFederationConfiguration.Issuer                 = issuer;
            federationConfiguration.WsFederationConfiguration.Realm                  = rpRealm;
            federationConfiguration.WsFederationConfiguration.RequireHttps           = requireSsl;
            federationConfiguration.WsFederationConfiguration.PassiveRedirectEnabled = true;

            return(federationConfiguration);
        }
示例#15
0
        public static FederationConfiguration Create(string relyingPartyUrl, string stsUrl, string domain, string certificateThumbprint, string authCookieName, bool requireSsl)
        {
            var federationConfiguration = new FederationConfiguration();

            federationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(relyingPartyUrl));

            var issuingAuthority = new IssuingAuthority(stsUrl);

            issuingAuthority.Thumbprints.Add(certificateThumbprint);
            issuingAuthority.Issuers.Add(stsUrl);
            var issuingAuthorities = new List <IssuingAuthority> {
                issuingAuthority
            };

            var validatingIssuerNameRegistry = new ValidatingIssuerNameRegistry {
                IssuingAuthorities = issuingAuthorities
            };

            federationConfiguration.IdentityConfiguration.IssuerNameRegistry        = validatingIssuerNameRegistry;
            federationConfiguration.IdentityConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;

            var chunkedCookieHandler = new ChunkedCookieHandler
            {
                RequireSsl = requireSsl,
                Name       = authCookieName,
                Domain     = domain,
                PersistentSessionLifetime = new TimeSpan(0, 0, 30, 0)
            };

            federationConfiguration.CookieHandler = chunkedCookieHandler;
            var issuerOfToken = stsUrl;

            federationConfiguration.WsFederationConfiguration.Issuer       = issuerOfToken;
            federationConfiguration.WsFederationConfiguration.Realm        = relyingPartyUrl;
            federationConfiguration.WsFederationConfiguration.RequireHttps = requireSsl;

            return(federationConfiguration);
        }
示例#16
0
        public static void RefreshKeys(string metadataLocation)
        {
            IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);

            bool newKeys = false;

            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                if (!ContainsKey(thumbprint))
                {
                    newKeys = true;
                    break;
                }
            }

            if (newKeys)
            {
                using (TenantDbContext context = new TenantDbContext())
                {
                    context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                    foreach (string thumbprint in issuingAuthority.Thumbprints)
                    {
                        context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey {
                            Id = thumbprint
                        });
                    }

                    foreach (string issuer in issuingAuthority.Issuers)
                    {
                        context.Tenants.Add(new Tenant {
                            Id = issuer.TrimEnd('/').Split('/').Last()
                        });
                    }

                    context.SaveChanges();
                }
            }
        }
示例#17
0
        //public override ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        //{
        //    //var identity = new GenericIdentity("*****@*****.**");

        //    //identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"));


        //    //ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);

        //    //validatedToken = new JwtSecurityToken("https://asemshop1.accesscontrol.windows.net/", "https://localhost/ACSWebShop/", new List<Claim>(), DateTime.Now.AddDays(-1), DateTime.Now.AddDays(10));

        //    //return claimsPrincipal;

        //    return base.ValidateToken(securityToken, validationParameters, out validatedToken);
        //}

        public override System.Collections.ObjectModel.ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            JwtSecurityToken jwtToken = (JwtSecurityToken)token;

            // Get the configuration from the configuration file (element "issuerNameRegistry").
            ValidatingIssuerNameRegistry issuerNameRegistry = (ValidatingIssuerNameRegistry)
                                                              Configuration.IssuerNameRegistry;

            IssuingAuthority issuingAuthority = issuerNameRegistry.IssuingAuthorities.First();

            // Set the validation parameters from the configuration.
            var validationParameters = new TokenValidationParameters
            {
                // Get the audiences that are expected.
                ValidAudiences = Configuration.AudienceRestriction.AllowedAudienceUris.Select(s => s.ToString()),

                // Get the issuer that are expected.
                ValidIssuers = issuingAuthority.Issuers,

                // Get the symmetric key token that is used to sign (if configured).
                // Did not get this one working though.
                IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(issuingAuthority.SymmetricKeys.FirstOrDefault())),

                // Get how to validate the certificate.
                CertificateValidator = Configuration.CertificateValidator,

                // Get if the token should be preserved.
                SaveSigninToken = Configuration.SaveBootstrapContext
            };

            // Call the correct validation method.
            SecurityToken   validatedToken;
            ClaimsPrincipal validated = ValidateToken(jwtToken.RawData, validationParameters, out validatedToken);

            // Return the claim identities.
            return(new ReadOnlyCollection <ClaimsIdentity>(validated.Identities.ToList()));
        }
示例#18
0
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // See the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            RoleEnvironment.Changing += RoleEnvironmentChanging;


            //Comment following code to debug the cloud service on local emulator

            #region Copy the config in web.config
            using (var server = new ServerManager())
            {
                string   siteNameFromServiceModel = "Web";
                string   siteName       = string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);
                string   configFilePath = server.Sites[siteName].Applications[0].VirtualDirectories[0].PhysicalPath + "\\Web.config";
                XElement element        = XElement.Load(configFilePath);

                string strSetting;

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("connectionString"))))
                {
                    var v = from appSetting in element.Element("connectionStrings").Elements("add")
                            where "WindowsAzureStorage" == appSetting.Attribute("name").Value
                            select appSetting;

                    if (v != null)
                    {
                        v.First().Attribute("connectionString").Value = strSetting;
                    }
                }

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("bingCredential"))))
                {
                    var v = from appSetting in element.Element("appSettings").Elements("add")
                            where "bingCredential" == appSetting.Attribute("key").Value
                            select appSetting;

                    if (v != null)
                    {
                        v.First().Attribute("value").Value = strSetting;
                    }
                }

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("FederationMetadataLocation"))))
                {
                    var v = from appSetting in element.Element("appSettings").Elements("add")
                            where "FederationMetadataLocation" == appSetting.Attribute("key").Value
                            select appSetting;

                    if (v != null)
                    {
                        v.First().Attribute("value").Value = strSetting;
                    }
                }

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("audienceUri"))))
                {
                    element.Element("system.identityModel").Element("identityConfiguration").Element("audienceUris").Element("add").Attribute("value").Value = strSetting;
                }

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("trustedIssuerName"))))
                {
                    element.Element("system.identityModel").Element("identityConfiguration").Element("issuerNameRegistry").Element("authority").Attribute("name").Value = strSetting;
                    element.Element("system.identityModel").Element("identityConfiguration").Element("issuerNameRegistry").Element("authority").Element("validIssuers").Element("add").Attribute("name").Value = strSetting;
                }

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("issuer"))))
                {
                    element.Element("system.identityModel.services").Element("federationConfiguration").Element("wsFederation").Attribute("issuer").Value = strSetting;
                }
                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("realm"))))
                {
                    element.Element("system.identityModel.services").Element("federationConfiguration").Element("wsFederation").Attribute("realm").Value = strSetting;
                }

                element.Save(configFilePath);

                if (!(String.IsNullOrEmpty(strSetting = RoleEnvironment.GetConfigurationSettingValue("FederationMetadataLocation"))))
                {
                    ValidatingIssuerNameRegistry.WriteToConfig(strSetting, configFilePath);
                }

                server.CommitChanges();
            }
            #endregion

            return(base.OnStart());
        }