Example #1
2
        private async void onVerifyClick(object sender, RoutedEventArgs e)
        {
            // do something
            string issuer = "";
            List<SecurityToken> signingTokens = null;
            try
            {
                string stsDiscoveryEndpoint = string.Format("{0}/.well-known/openid-configuration", authority);
                ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
                
                OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync();
                issuer = config.Issuer;
                signingTokens = config.SigningTokens.ToList();
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

                TokenValidationParameters validationParameters = new TokenValidationParameters
                {
                    ValidAudience = audience,
                    ValidIssuer = issuer,
                    IssuerSigningTokens = signingTokens,
                    CertificateValidator = X509CertificateValidator.None
                };

                // Validate token.
                SecurityToken validatedToken = new JwtSecurityToken();
                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(m_access_token, validationParameters, out validatedToken);

                var puid = claimsPrincipal.FindFirst(@"puid");
                MessageBox.Show("Verify Access token success! ");

            }
            catch(Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Verifing Access token get Inner Exception : " + ex.InnerException.Message;
                }
                MessageBox.Show(message);
            }
        }
Example #2
0
        private static Configuration GetUserConfig(Project project, string assemblyFullName)
        {
            DebugCheck.NotNull(project);

            var userConfigFilename
                = Path.Combine(
                      (string)project.Properties.Item("FullPath").Value,
                      project.IsWebProject()
                        ? "Web.config"
                        : "App.config");

            var document = XDocument.Load(userConfigFilename);

            FixUpConfig(document, assemblyFullName);

            var tempFile = Path.GetTempFileName();

            document.Save(tempFile);

            return(ConfigurationManager.OpenMappedExeConfiguration(
                       new ExeConfigurationFileMap {
                ExeConfigFilename = tempFile
            },
                       ConfigurationUserLevel.None));
        }
Example #3
0
        /// <summary>
        /// Attempts to find a database connection string for a project.
        /// </summary>
        /// <param name="project">The project to search for a connection string</param>
        public SqlConnectionStringBuilder Locate(Project project)
        {
            // Try to find the app config file.
            var configItem = project.TryFindChild(item => !String.IsNullOrEmpty(item.Name) && ConfigNamePattern.IsMatch(item.Name));

            if (configItem == null)
            {
                throw new ConnectionStringLocationException("Valid config file could not be found.");
            }

            var configFile = new ExeConfigurationFileMap {
                ExeConfigFilename = configItem.FileNames[0]
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
            var connectionStringSettings = config.ConnectionStrings.ConnectionStrings
                                           .Cast <ConnectionStringSettings>()
                                           .Reverse()
                                           .FirstOrDefault(cs => cs.ProviderName == EntityProviderName);

            if (connectionStringSettings == null)
            {
                throw new ConnectionStringLocationException($"Connection string for provider '{EntityProviderName}' not found.");
            }

            var entityConnString = new DbConnectionStringBuilder
            {
                ConnectionString = connectionStringSettings.ConnectionString
            };
            var connectionString = (string)entityConnString[ProviderConnectionStringKey];

            return(new SqlConnectionStringBuilder(connectionString));
        }
Example #4
0
        private void ChangeFoowwEnvironmentToTest(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string appConfigPath              = GetStartupProjectDirectoryPath() + @"\app.config";
            string environmentNode            = "Environment";
            ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();

            configMap.ExeConfigFilename = appConfigPath;
            Configuration appConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            // 没有配置,需要新增测试环境配置
            if (!appConfig.AppSettings.Settings.AllKeys.Contains(environmentNode))
            {
                appConfig.AppSettings.Settings.Add(environmentNode, "Test");
                appConfig.Save(ConfigurationSaveMode.Modified);
                //使connectionStrings配置节缓存失效,下次必须从磁盘读取
                ConfigurationManager.RefreshSection("appSettings");
                return;
            }

            // 否则改为测试
            string value = appConfig.AppSettings.Settings[environmentNode].Value;

            if (value.ToLower() != "test")
            {
                appConfig.AppSettings.Settings[environmentNode].Value = "Test";
                appConfig.Save(ConfigurationSaveMode.Modified);
                //使connectionStrings配置节缓存失效,下次必须从磁盘读取
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
Example #5
0
        public static void UpdateDailyAnnoucement(int h, int m, int s, int interval, int loops, string command)
        {
            Configuration config = ConfManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            string delim = ConfManager.AppSettings["AnnMess"] == "" ? "" : "|";

            string annMess     = ConfManager.AppSettings["AnnMess"] + delim + command;
            string annTime     = ConfManager.AppSettings["AnnTime"] + delim + h + ":" + m;
            string annLoops    = ConfManager.AppSettings["AnnLoops"] + delim + loops;
            string annInterval = ConfManager.AppSettings["AnnInterval"] + delim + interval;

            config.AppSettings.Settings["AnnMess"].Value     = annMess;
            config.AppSettings.Settings["AnnTime"].Value     = annTime;
            config.AppSettings.Settings["AnnLoops"].Value    = annLoops;
            config.AppSettings.Settings["AnnInterval"].Value = annInterval;
            config.Save(ConfigurationSaveMode.Modified);
            ConfManager.RefreshSection("appSettings");


            //TelepresenceScheduler.DeleteDailyAnnouncement();
            //LoadDailyAnnouncement();
            Action action = new Action(() =>
            {
                SpeechGeneration.SpeakAsync(command);
            });

            TelepresenceScheduler.DailyIntervalInSeconds(h, m, s, interval, loops, action);
        }
Example #6
0
        private static AppConfiguration Load(IFileSystemInfo info)
        {
            var file = ResolveFile(info);

            var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                using (var destination = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite))
                    using (var source = file.OpenRead())
                    {
                        source.CopyTo(destination);
                    }

                var configuration = Manager.OpenMappedExeConfiguration(new ExeConfigurationFileMap {
                    ExeConfigFilename = tempFile
                }, ConfigurationUserLevel.None);
                return((AppConfiguration)configuration.GetSection(AppConfiguration.SectionName));
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Example #7
0
        private ConnectionStringSettings GetConnectionStringSettings(ProjectItem item, string name)
        {
            Property property = item.FindProperty(ProjectItemProperty.FullPath);
            var      exeConfigurationFileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = property.Value.ToString()
            };
            Configuration            configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
            ConnectionStringsSection strings       = configuration.ConnectionStrings;

            return(strings.ConnectionStrings[name]);
        }
        public static void DeleteDailyAnnouncement()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);


            config.AppSettings.Settings["AnnMess"].Value     = "";
            config.AppSettings.Settings["AnnTime"].Value     = "";
            config.AppSettings.Settings["AnnLoops"].Value    = "";
            config.AppSettings.Settings["AnnInterval"].Value = "";
            config.Save(ConfigurationSaveMode.Modified);
            ConfManager.RefreshSection("appSettings");
            SchedulerService.DeleteAllTimersForEveryday();
        }
Example #9
0
        private static Configuration GetUserConfig(Project project)
        {
            Contract.Requires(project != null);

            var userConfigFilename
                = Path.Combine(
                      (string)project.Properties.Item("FullPath").Value,
                      project.IsWebProject()
                        ? "Web.config"
                        : "App.config");

            return(ConfigurationManager.OpenMappedExeConfiguration(
                       new ExeConfigurationFileMap {
                ExeConfigFilename = userConfigFilename
            },
                       ConfigurationUserLevel.None));
        }
        public ArchivizerConfiguration ReadConfiguration()
        {
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = "ArchivizerConfiguration.config"
            };
            var config = SystemConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            var globalConfiguration = config.GetSection("GlobalConfigurationSection") as GlobalConfigurationSection;
            var supportedDirectory  = config.GetSection("SupportedArchivizerConfigurationForDirectorySection") as SupportedArchivizerConfigurationForDirectorySection;

            var configurations = supportedDirectory.GetConfiguration();

            var configuration = new ArchivizerConfiguration
            {
                Achivizer7zFullName                  = globalConfiguration.Archivizer7zFullName,
                DeleteSourceFileAfterArchiving       = globalConfiguration.DeleteSourceFileAfterArchiving,
                ArchivizerConfigurationsForDirectory = new ReadOnlyDictionary <string, ArchivizerConfigurationForDirectory>(configurations),
                MaxNumberOfLatestArchiveFilesInKept  = globalConfiguration.MaxNumberOfLatestArchiveFilesInKept
            };

            ValidateConfiguration(configuration);
            return(configuration);
        }
Example #11
0
 static Cfg()
 {
     _conf    = ConfManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     _section = (StartupFoldersConfigSection)_conf.GetSection("StartupFolders");
 }
Example #12
0
        //
        // SendAsync checks that incoming requests have a valid access token, and sets the current user identity using that access token.
        //
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string authHeader = null;
            string jwtToken = null;
            string issuer;
            string stsDiscoveryEndpoint = string.Format("{0}/.well-known/openid-configuration", authority);

            List<SecurityToken> signingTokens;

            // The header is of the form "bearer <accesstoken>", so extract to the right of the whitespace to find the access token.
            authHeader = HttpContext.Current.Request.Headers["Authorization"];
            if (authHeader != null)
            {
                int startIndex = authHeader.LastIndexOf(' ');
                if (startIndex > 0)
                {
                    jwtToken = authHeader.Substring(startIndex).Trim();
                }
            }

            if (jwtToken == null)
            {
                HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
                return response;
            }

            try
            {
                // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.            
                if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24
                    || string.IsNullOrEmpty(_issuer)
                    || _signingTokens == null)
                {
                    // Get tenant information that's used to validate incoming jwt tokens
                    ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
                    OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync();
                    _issuer = config.Issuer;
                    _signingTokens = config.SigningTokens.ToList();

                    _stsMetadataRetrievalTime = DateTime.UtcNow;
                }

                issuer = _issuer;
                signingTokens = _signingTokens;
            }
            catch (Exception)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidAudience = audience,
                ValidIssuer = issuer,
                IssuerSigningTokens = signingTokens,
                CertificateValidator = X509CertificateValidator.None                 
            };

            try
            {
                // Validate token.
                SecurityToken validatedToken = new JwtSecurityToken();
                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);

                // Set the ClaimsPrincipal on the current thread.
                Thread.CurrentPrincipal = claimsPrincipal;

                // Set the ClaimsPrincipal on HttpContext.Current if the app is running in web hosted environment.
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = claimsPrincipal;
                }

                // If the token is scoped, verify that required permission is set in the scope claim.
                if (ClaimsPrincipal.Current.FindFirst(scopeClaimType) != null && ClaimsPrincipal.Current.FindFirst(scopeClaimType).Value != "user_impersonation")
                {
                    HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Forbidden);
                    return response;
                }

                return await base.SendAsync(request, cancellationToken);
            }
            catch (SecurityTokenValidationException)
            {
                HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
                return response;
            }
            catch (Exception)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
        }
Example #13
0
 private static AppConfiguration LoadCurrent()
 {
     return((AppConfiguration)Manager.GetSection(AppConfiguration.SectionName));
 }
Example #14
0
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

#if true // my reimplementation
            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
            }
            ApplicationSettingsBase asb       = context.CurrentSettings;
            string class_name                 = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
            ClientSettingsSection userSection = null;
            ConfigurationSection  cnf         = userGroup.Sections.Get(class_name);
            userSection = cnf as ClientSettingsSection;
            if (userSection == null)
            {
                userSection = new ClientSettingsSection();
                userGroup.Sections.Add(class_name, userSection);
            }

            bool hasChanges = false;

            if (userSection == null)
            {
                return;
            }

            foreach (SettingsPropertyValue value in collection)
            {
                if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                {
                    continue;
                }
                // The default impl does not save the ApplicationScopedSetting properties
                if (value.Property.Attributes.Contains(typeof(ApplicationScopedSettingAttribute)))
                {
                    continue;
                }

                hasChanges = true;
                SettingElement element = userSection.Settings.Get(value.Name);
                if (element == null)
                {
                    element = new SettingElement(value.Name, value.Property.SerializeAs);
                    userSection.Settings.Add(element);
                }
                if (element.Value.ValueXml == null)
                {
                    element.Value.ValueXml = new XmlDocument().CreateElement("value");
                }
                switch (value.Property.SerializeAs)
                {
                case SettingsSerializeAs.Xml:
                    element.Value.ValueXml.InnerXml = (value.SerializedValue as string) ?? string.Empty;
                    break;

                case SettingsSerializeAs.String:
                    element.Value.ValueXml.InnerText = value.SerializedValue as string;
                    break;

                case SettingsSerializeAs.Binary:
                    element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
#else // original impl. - likely buggy to miss some properties to save
            foreach (ConfigurationSection configSection in userGroup.Sections)
            {
                ClientSettingsSection userSection = configSection as ClientSettingsSection;
                if (userSection != null)
                {
/*
 *                                      userSection.Settings.Clear();
 *
 *                                      foreach (SettingsPropertyValue propertyValue in collection)
 *                                      {
 *                                              if (propertyValue.IsDirty)
 *                                              {
 *                                                      SettingElement element = new SettingElement(propertyValue.Name, SettingsSerializeAs.String);
 *                                                      element.Value.ValueXml = new XmlDocument();
 *                                                      element.Value.ValueXml.InnerXml = (string)propertyValue.SerializedValue;
 *                                                      userSection.Settings.Add(element);
 *                                              }
 *                                      }
 */
                    foreach (SettingElement element in userSection.Settings)
                    {
                        if (collection [element.Name] != null)
                        {
                            if (collection [element.Name].Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                            {
                                continue;
                            }

                            element.SerializeAs             = SettingsSerializeAs.String;
                            element.Value.ValueXml.InnerXml = (string)collection [element.Name].SerializedValue;                                ///Value = XmlElement
                        }
                    }
                }
            }
            config.Save(ConfigurationSaveMode.Minimal, true);
#endif
        }
Example #15
0
        // Ensure that initialization has completed, while handling re-entrancy issues
        // for certain sections that may be used during initialization itself.
        void EnsureInit(string configKey)
        {
            bool doInit = false;

            lock (this) {
                // If the user config is not initialized, then we must either:
                //    a. Perform the initialization ourselves if no other thread is doing it, or
                //    b. Wait for the initialization to complete if we know the section is not used during initialization itself, or
                //    c. Ignore initialization if the section can be used during initialization. Note that GetSection()
                //       returns null is initialization has not completed.
                if (!_isUserConfigInited)
                {
                    if (!_isInitInProgress)
                    {
                        _isInitInProgress = true;
                        doInit            = true;
                    }
                    else if (!IsSectionUsedInInit(configKey))
                    {
                        // Wait for initialization to complete.
                        Monitor.Wait(this);
                    }
                }
            }

            if (doInit)
            {
                try {
                    try {
                        try {
                            // Initialize machine configuration.
                            _machineConfigRecord = _configRoot.GetConfigRecord(
                                ClientConfigurationHost.MachineConfigPath);

                            _machineConfigRecord.ThrowIfInitErrors();

                            // Make machine configuration available to system.net sections
                            // when application configuration is downloaded via http.
                            _isMachineConfigInited = true;

                            //
                            // Prevent deadlocks in the networking classes by loading
                            // networking config before making a networking request.
                            // Any requests for sections used in initialization during
                            // the call to EnsureConfigLoaded() will be served by
                            // _machine.config or will return null.
                            //
                            if (_isAppConfigHttp)
                            {
                                ConfigurationManagerHelperFactory.Instance.EnsureNetConfigLoaded();
                            }

                            //
                            // Now load the rest of configuration
                            //
                            _configHost.RefreshConfigPaths();
                            string configPath;
                            if (_configHost.HasLocalConfig)
                            {
                                configPath = ClientConfigurationHost.LocalUserConfigPath;
                            }
                            else if (_configHost.HasRoamingConfig)
                            {
                                configPath = ClientConfigurationHost.RoamingUserConfigPath;
                            }
                            else
                            {
                                configPath = ClientConfigurationHost.ExeConfigPath;
                            }

                            _completeConfigRecord = _configRoot.GetConfigRecord(configPath);
                            _completeConfigRecord.ThrowIfInitErrors();

                            _isUserConfigInited = true;
                        }
                        catch (Exception e) {
                            _initError = new ConfigurationErrorsException(SR.GetString(SR.Config_client_config_init_error), e);
                            throw _initError;
                        }
                        catch {
                            _initError = new ConfigurationErrorsException(SR.GetString(SR.Config_client_config_init_error));
                            throw _initError;
                        }
                    }
                    catch {
                        ConfigurationManager.SetInitError(_initError);
                        _isMachineConfigInited = true;
                        _isUserConfigInited    = true;
                        throw;
                    }
                }
                finally {
                    lock (this) {
                        try {
                            // Notify ConfigurationSettings that initialization has fully completed,
                            // even if unsuccessful.
                            ConfigurationManager.CompleteConfigInit();

                            _isInitInProgress = false;
                        }
                        finally {
                            // Wake up all threads waiting for initialization to complete.
                            Monitor.PulseAll(this);
                        }
                    }
                }
            }
        }
Example #16
0
 public static object GetConfig(string sectionName)
 {
     return(ConfigurationManager.GetSection(sectionName));
 }