private static void SetCredentials(WebClient wc) { var userName = GetConfigServiceUser(); var password = GetConfigServicePassword(); if (UseAzureAd) { var token = HasCredentilas(userName, password) ? GetBearerToken(userName, password) : GetBearerToken(); wc.Headers.Add("Authorization", token); return; } if (ConfigurationManagerHelper.GetValueOnKey("stardust.useAccessToken") == "true") { wc.Headers.Add(HttpRequestHeader.Authorization, "Token " + Convert.ToBase64String(ConfigurationManagerHelper.GetValueOnKey("stardust.accessToken").GetByteArray())); if (GetTokenKey().ContainsCharacters()) { wc.Headers.Add("key", GetTokenKey()); } return; } if (userName.ContainsCharacters() && password.ContainsCharacters()) { wc.Credentials = new NetworkCredential(userName, password, GetConfigServiceDomain()); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { Stardust.Interstellar.Rest.Service.ServiceFactory.ThrowOnException = true; services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddVeracity(Configuration) .AddScoped(s => s.GetService <IHttpContextAccessor>().HttpContext.User) //.AddSingleton(ConstructDistributedCache) //.AddDistributedRedisCache(opt => //{ // opt.Configuration = Configuration.GetSection("Veracity").GetValue<string>("RedisConnectionString"); // opt.InstanceName = "master3"; //}) //.AddMemoryCache() .AddSingleton(ConstructDistributedCache) .AddVeracityServices(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url")) .AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddVeracityAuthentication(Configuration) .AddCookie(); services.AddMvc(options => options.EnableEndpointRouting = false).AddVeracityApiProxies(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url")).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
static ContextScopeExtensions() { if (ConfigurationManagerHelper.GetValueOnKey("stardust.enableOlmCleaningTask", false)) { PeriodicTask.Run(CleanStateCache, null, TimeSpan.FromMinutes(10), CancellationToken.None); } }
public Binding Create(Endpoint serviceInterface) { var binding = new BasicHttpBinding { Name = serviceInterface.EndpointName, AllowCookies = false, HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard), MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize, MaxReceivedMessageSize = serviceInterface.MaxReceivedSize, MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Mtom), MaxBufferSize = serviceInterface.MaxBufferSize, TransferMode = TransferMode.Streamed, TextEncoding = Encoding.UTF8, ReaderQuotas = XmlDictionaryReaderQuotas.Max, BypassProxyOnLocal = true, UseDefaultWebProxy = false, }; if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true") { binding.BypassProxyOnLocal = false; binding.UseDefaultWebProxy = true; } return(binding); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddVeracity(Configuration) .AddScoped <IOAuthTokenProvider, TokenProvider>() .AddSingleton <TokenProviderConfiguration, TokenProviderConfiguration>() .AddHttpContextAccessor() .AddSingleton <ILogger, LogWrapper>() .AddSingleton <ILogging, LogWrapper>() .AddScoped(s => s.GetService <IHttpContextAccessor>().HttpContext.User) .AddSingleton(ConstructDataProtector) .AddSingleton(ConstructDistributedCache) .AddDistributedRedisCache(opt => { opt.Configuration = Configuration.GetSection("Veracity").GetValue <string>("RedisConnectionString"); opt.InstanceName = "master"; }) .AddScoped <TokenCacheBase, DistributedTokenCache>() .AddVeracityServices(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url")) .AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddVeracityAuthentication(Configuration) .AddCookie(); services.AddMvc() .AddVeracityApiProxies(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url"), CookieAuthenticationDefaults.AuthenticationScheme); }
public Binding Create(Endpoint serviceInterface) { System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); var secureBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential) { Name = "secure", TransactionFlow = false, HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard), MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize, MaxReceivedMessageSize = serviceInterface.MaxReceivedSize, MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text), TextEncoding = Encoding.UTF8, ReaderQuotas = XmlDictionaryReaderQuotas.Max, BypassProxyOnLocal = true, UseDefaultWebProxy = false }; if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true") { secureBinding.BypassProxyOnLocal = false; secureBinding.UseDefaultWebProxy = true; } SetSecuritySettings(serviceInterface, secureBinding); return(secureBinding); }
internal static ConfigurationSet GetConfiguration(string id, string env, string localFile, bool skipSave = false) { ConfigurationSet configData; var req = WebRequest.Create(CreateRequestUriString(id, env)) as HttpWebRequest; req.Method = "GET"; req.Accept = "application/json"; req.ContentType = "application/json"; req.Headers.Add("Accept-Language", "en-us"); req.UserAgent = "StardustProxy/1.0"; req.Credentials = new NetworkCredential( ConfigurationManagerHelper.GetValueOnKey("stardust.configUser"), ConfigurationManagerHelper.GetValueOnKey("stardust.configPassword"), ConfigurationManagerHelper.GetValueOnKey("stardust.configDomain")); req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; var resp = req.GetResponse(); using (var reader = new StreamReader(resp.GetResponseStream())) { configData = JsonConvert.DeserializeObject <ConfigurationSet>(reader.ReadToEnd()); if (!skipSave) { ConfigCacheHelper.UpdateCache(localFile, configData, new ConfigWrapper { Set = configData, Environment = env, Id = id }); } } return(configData); }
/// <summary> /// This is called by WebActivator in web applications and must be /// called manually when used in other application types. This method initializes /// the framework. If you only use the IoC container and not the entire /// SOA framework add stardust.OnlyIoC= true to web.config -> /// appSettings in order to load only the needed components. If you use /// the SOA framework inherit from /// <see cref="CoreFrameworkBlueprint" /> to apply your own /// bindings as well as binding the framework it self. Load the binding /// configurations by calling Resolver.LoadModuleConfiguration() /// </summary> public static void InitializeModules() { try { var c = ConfigurationHelper.Configurations.Value; if (c != null && c.BindingConfigurationType != null) { Resolver.LoadModuleConfiguration(); var appInitializer = Resolver.Activate <IStardustWebInitializer>(); if (appInitializer.IsInstance()) { DynamicModuleUtility.RegisterModule(typeof(StardustWebInitializer)); } } } catch { } if (ConfigurationManagerHelper.GetValueOnKey("stardust.OnlyIoC") == "true") { Resolver.LoadModuleConfiguration <CoreFrameworkBlueprint>(); } else { new WebServerConfiguration().PrepWebServer(null); } }
public Binding Create(Endpoint serviceInterface) { if (Utilities.Utilities.GetDisableCertificateValidation().EqualsCaseInsensitive("true")) { System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); } var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) { Name = serviceInterface.EndpointName, AllowCookies = false, HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard), MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize, MaxReceivedMessageSize = serviceInterface.MaxReceivedSize, MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text), TextEncoding = Encoding.UTF8, ReaderQuotas = XmlDictionaryReaderQuotas.Max, BypassProxyOnLocal = true, UseDefaultWebProxy = false }; if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true") { binding.BypassProxyOnLocal = false; binding.UseDefaultWebProxy = true; } binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; return(binding); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { Stardust.Interstellar.Rest.Service.ServiceFactory.ThrowOnException = true; services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddVeracity(Configuration) .AddScoped(s => s.GetService <IHttpContextAccessor>().HttpContext.User) .AddSingleton(ConstructDistributedCache) .AddVeracityServices(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url"), services => services.AddScoped(s => s.CreateRestClient <IWtfClient>("https://localhost:44344/"))) .AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddVeracityAuthentication(Configuration, isMfaRequiredOptions: (httpContext, authenticationProperties) => { //do custom logic there return(true); }) .AddCookie(); services.AddMvc(options => options.EnableEndpointRouting = false) .AddAsController <ITestService, TestApi>() .AddVeracityApiProxies(ConfigurationManagerHelper.GetValueOnKey("myApiV3Url")) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public KeenLogger() { Logger = new LoggingDefaultImplementation(); if (!ConfigurationManagerHelper.GetValueOnKey("stardust.logToKeen", false)) { return; } try { if (keenClient != null) { return; } var prjSettings = new ProjectSettingsProvider(GetProjectId(), writeKey: GetProjectKey()); keenClient = new KeenClient(prjSettings); keenClient.AddGlobalProperty("serviceHost", Utilities.GetServiceName()); keenClient.AddGlobalProperty("environment", "Config"); keenClient.AddGlobalProperty("configSet", "ALL"); keenClient.AddGlobalProperty("machine", Environment.MachineName); keenClient.AddGlobalProperty("datacenterKey", "cnfpxwe"); var prjReadSettings = new ProjectSettingsProvider(GetProjectId(), readKey: GetProjectReadKey()); keenReadClient = new KeenClient(prjReadSettings); } catch (Exception) { } }
private TestContext TestContext() { JsonConvert.DefaultSettings = () => { return(new JsonSerializerSettings { Formatting = Formatting.Indented, Error = (sender, args) => { Logging.DebugMessage(""); }, }.RegisterGraphSerializer()); }; //var tc = new TestContext(new Class1()); var tc = new TestContext(new GremlinNetLanguageConnector($"{ConfigurationManagerHelper.GetValueOnKey("cosmosDbAccount")}.gremlin.cosmosdb.azure.com", "graphTest", "services", ConfigurationManagerHelper.GetValueOnKey("cosmosDbKey"))); tc.OnDisposing = c => { c.SaveChangesError -= OnTcOnSaveChangesError; c.SavingChanges -= OnTcOnSavingChanges; c.ChangesSaved -= OnTcOnChangesSaved; }; tc.Disposing += Tc_Disposing; tc.SavingChanges += OnTcOnSavingChanges; tc.ChangesSaved += OnTcOnChangesSaved; tc.SaveChangesError += OnTcOnSaveChangesError; return(tc); }
private static void AddCommonSwaggerSettings(Action <SwaggerGenOptions> customOptions, SwaggerGenOptions c) { c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(AuthorizationUrl(ConfigurationManagerHelper.GetValueOnKey("tenantId"), true)), Scopes = AcceptScopeAttribute.AllScopes.Distinct().ToDictionary( k => $"{ConfigurationManagerHelper.GetValueOnKey("resourceId")}/{k.Item1}", v => v.Item2) } } }); c.CustomSchemaIds((type) => type.ToString() .Replace("[", "_") .Replace("]", "_") .Replace(",", "-") .Replace("`", "_") ); c.IgnoreObsoleteActions(); c.IgnoreObsoleteProperties(); c.SwaggerGeneratorOptions.OperationFilters.Add(new SecurityRequirementsOperationFilter()); customOptions?.Invoke(c); }
public virtual Binding Create(Endpoint serviceInterface) { var binding = new WSHttpBinding(SecurityMode.Transport) { Name = serviceInterface.EndpointName, AllowCookies = false, TransactionFlow = false, HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard), MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize, MaxReceivedMessageSize = serviceInterface.MaxReceivedSize, MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text), TextEncoding = Encoding.UTF8, ReaderQuotas = XmlDictionaryReaderQuotas.Max, BypassProxyOnLocal = true, UseDefaultWebProxy = false }; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true") { binding.BypassProxyOnLocal = false; binding.UseDefaultWebProxy = true; } return(binding); }
private static void SetMessageValuesIfNotSetInClient(IRequestBase message, IRuntime runtime) { if (message.MessageId.IsNullOrWhiteSpace()) { message.MessageId = Guid.NewGuid().ToString(); } if (message.Environment.IsNullOrWhiteSpace()) { message.Environment = runtime.Environment; } if (message.ServiceName.IsNullOrWhiteSpace()) { message.ServiceName = runtime.ServiceName; } if (message.ConfigSet.IsNullOrWhiteSpace()) { message.ConfigSet = ConfigurationManagerHelper.GetValueOnKey("configSet"); } if (message.TimeStamp == null) { message.TimeStamp = DateTime.UtcNow; } if (runtime.RequestContext.IsInstance()) { message.ReferingMessageId = runtime.RequestContext.MessageId; } }
public static string ResolveThumbprint(string thumbprint, string issuerAddress) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.LiveSingingTokenThumbprint") == "false") { return(thumbprint); } var thumbprintCahced = GetCachedThumbprint(issuerAddress); if (thumbprintCahced.ContainsCharacters()) { return(thumbprintCahced); } var cert = GetThumbprintFromMetadata(issuerAddress); if (cert.IsInstance()) { thumbprint = cert.Thumbprint; CacheIssuerThumbprint(cert, issuerAddress); } else { CacheIssuerThumbprint(thumbprint, issuerAddress); } return(thumbprint); }
private void context_AuthenticateRequest(object sender, EventArgs e) { try { var context = sender as HttpApplication; if (!IsService(sender, context)) { return; } if (ConfigurationManagerHelper.GetValueOnKey("statdust.forceJsonOnWfc", true)) { if (context.Request.ContentType.Contains("xml")) { context.Request.ContentType = context.Request.ContentType.Replace("xml", "json"); } } var auth = context.Request.Headers["Authorization"]; var credentials = AuthenticationHeaderValue.Parse(auth); if (context.Request.Headers["Authorization"] != null) { LogIn(context); } } catch (Exception ex) { ex.Log(); HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.Forbidden; HttpContext.Current.Response.End(); } }
/// <summary>Initializes a new instance of the <see cref="T:System.Attribute" /> class.</summary> public ConfiguredClienUserAgentName() { if (string.IsNullOrWhiteSpace(configuredValue)) { configuredValue = ConfigurationManagerHelper.GetValueOnKey("stardust.clientUserAgentName"); } }
static ThumbprintResolver() { if (ConfigurationManagerHelper.GetValueOnKey("stardust.LiveSingingTokeThumbprint") == "false") { return; } //RefreshTime = new Timer(RefreshThumbprintsTokens, null, new TimeSpan(0), new TimeSpan(0, 0, 10, 0)); }
private static string MakeConnectionString(string raw) { if (Encrypted) { return(raw.Encrypt(new EncryptionKeyContainer(ConfigurationManagerHelper.GetValueOnKey("stardust.ConfigKey", "this is just bullshit")))); } return(raw); }
// GET: Migration public ActionResult Index() { ViewBag.CurentConfigDatabase = RepositoryFactory.GetConnectionString().Split(';').Last().Split('=').Last(); var stores = Directory.EnumerateDirectories(ConfigurationManagerHelper.GetValueOnKey("stardust.StoreLocation")) .Select(d => d.Split('\\').LastOrDefault()); return(View(stores)); }
private List <EnvironmentConfig> GetEnvironmentConfigs(string environment) { if (ConfigurationManagerHelper.GetValueOnKey("stardust.IncludeAllEnvironments") == "true") { (from e in Environments select e.GetRawConfigData()).ToList(); } return((from e in Environments where e.Name.Equals(environment, StringComparison.OrdinalIgnoreCase) select e.GetRawConfigData()).ToList()); }
private static FaultException ConstructGenericError() { if (ConfigurationManagerHelper.GetValueOnKey("stardust.useWcfWebFault", false)) { return(new WebFaultException(HttpStatusCode.InternalServerError)); } return(new FaultException(new FaultReason("An unknown error occurred"))); }
public static AuthenticationResult GetToken(string serviceName) { var ctx = new AuthenticationContext(IdentitySettings.IssuerAddress, new NativeTokenCache()); var resource = Resource(serviceName); var appClientId = RuntimeFactory.Current.Context.GetServiceConfiguration().GetConfigParameter("OauthClientId"); var appClientSecret = RuntimeFactory.Current.Context.GetServiceConfiguration().GetSecureConfigParameter("OauthClientSecret"); try { AuthenticationResult token; var userToken = GetUserToken(); var userId = GetUserObjectId(); var clientCredential = new ClientCredential(appClientId, appClientSecret); if (userToken.ContainsCharacters()) { try { token = ctx.AcquireToken(resource, clientCredential, new UserAssertion(userToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", RuntimeFactory.Current.GetCurrentClaimsIdentity().Name)); } catch (Exception) { token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion()); } } else if (userId.ContainsCharacters()) { token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion()); } else { if (ConfigurationManagerHelper.GetValueOnKey("stardust.promptUserFOrCredentials", false)) { token = ctx.AcquireToken(resource, appClientId, new Uri("http://" + Utilities.GetEnvironment() + "ters.dnvgl.com"), PromptBehavior.Auto); } else { token = ctx.AcquireToken(resource, clientCredential); } } return(token); } catch (AdalSilentTokenAcquisitionException adalex) { if (adalex.ErrorCode == AdalError.FailedToAcquireTokenSilently) { HttpContext.Current.GetOwinContext().Authentication.SignOut(); HttpContext.Current.GetOwinContext().Authentication.Challenge(); throw; } throw; } catch (System.Exception ex) { ex.Log(); throw; } }
public Class1() { if (_client == null) { _client = new DocumentClient( new Uri($"https://{ConfigurationManagerHelper.GetValueOnKey("cosmosDbAccount")}.documents.azure.com:443/"), ConfigurationManagerHelper.GetValueOnKey("cosmosDbKey")); } }
private static int DefaultPoolSize() { var poolSize = ConfigurationManagerHelper.GetValueOnKey("defaultPoolSize"); if (poolSize.ContainsCharacters()) { return(Int32.Parse(poolSize)); } return(20); }
public static string GetConfigServiceUrl() { var cnf = ConfigurationManagerHelper.GetValueOnKey("configServiceUrl"); if (cnf.IsNullOrWhiteSpace()) { return("http://localhost:4651"); } return(cnf); }
private static RequestCacheLevel GetCahceLevel() { var config = ConfigurationManagerHelper.GetValueOnKey("stardust.ConfigReaderCache"); if (config.ContainsCharacters()) { return(config.ParseAsEnum(RequestCacheLevel.Revalidate)); } return(RequestCacheLevel.NoCacheNoStore); }
public static string GetPathFormat() { var pathFormat = ConfigurationManagerHelper.GetValueOnKey("stardust.FilePathFormat"); if (pathFormat.IsNullOrWhiteSpace()) { return(GetDirectory() + "\\{0}_{1}.json"); } return(String.Format("{0}{1}{2}", AppDomain.CurrentDomain.BaseDirectory + "\\App_Data", (pathFormat.StartsWith("\\") ? "" : "\\"), pathFormat)); }
public string GetConfigParameter(string name) { if (ConfigSet == null) { return(ConfigurationManagerHelper.GetValueOnKey(name)); } var envVal = GetEnvironmentConfiguration().GetConfigParameter(name); return(envVal.ContainsCharacters() ? envVal : ConfigurationManagerHelper.GetValueOnKey(name)); }