public void TestInitialize() { _mockHttp = new MockHttpMessageHandler(); _stsService = new StsService(new HttpClient(_mockHttp)); _mockHttp.When($"{_stsService.ApiUrl}/connect/token") .Respond("application/json", "{ \"access_token\": \"token\" }"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("default", policy => { policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddMvc(); services.AddIdentityServer(x => x.IssuerUri = Environment.GetEnvironmentVariable("ISSUER_URI")) .AddSigningCredential(_cert) .AddMongoRepository() .AddClients() .AddIdentityApiResources() .AddPersistedGrants() .AddProfileService <ProfileService>(); services.AddTransient <IResourceOwnerPasswordValidator, CustomResourceOwnerPasswordValidator>(); services.AddTransient <IProfileService, ProfileService>(); services.AddTransient <IPersistedGrantStore, CustomPersistedGrantStore>(); services.AddSingleton <ICorsPolicyService, CustomCorsPolicyService>(); var stsService = new StsService(); var mailService = new MailService(stsService); services.AddSingleton <IStsService>(stsService); services.AddSingleton <IMailService>(mailService); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new X509SecurityKey(_cert), ValidIssuers = Environment.GetEnvironmentVariable("ISSUERS").Split(","), ValidAudiences = Environment.GetEnvironmentVariable("AUDIENCE").Split(","), ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = tokenValidationParameters; options.SaveToken = true; }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build(); }); }
/// <summary> /// Initialize the test client /// </summary> /// <param name="site">TestSite from PTF</param> public void Initialize(ITestSite site) { testSite = site; httpServer = HttpServer.GetInstance(); // sts = new StsService(Constraints.HTTPSServiceDefaultPort); sts = new StsService(); X509Certificate2 cert = null; try { cert = new X509Certificate2(EnvironmentConfig.TLSServerCertificatePath, EnvironmentConfig.TLSServerCertificatePassword); } catch { site.Assert.Fail("Failed to load certificate as in PTFConfig: " + EnvironmentConfig.TLSServerCertificatePath + " with password:"******"Failed to init discovery or enrollment service endpoint" + (e.Message == null ? "" : (" due to reason: " + e.Message))); } }
public static IHostBuilder CreateLinuxHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog() .UseSystemd() .ConfigureServices((hostContext, sc) => { sc.AddSingleton <IConfiguration>(_conf); sc.AddSingleton <IContextService>(_instance); sc.AddSingleton <ILogger>(_logger); sc.AddSingleton <IMapper>(_mapper); sc.AddTransient <IUnitOfWork, UnitOfWork>(_ => { return(new UnitOfWork(_conf["Databases:AuroraEntities"], _instance)); }); sc.AddTransient <IAlertService, AlertService>(_ => { var alert = new AlertService(_conf); alert.Grant = new ResourceOwnerGrantV2(_conf); return(alert); }); sc.AddTransient <IAdminService, AdminService>(_ => { var admin = new AdminService(_conf); admin.Grant = new ResourceOwnerGrantV2(_conf); return(admin); }); sc.AddTransient <IStsService, StsService>(_ => { var sts = new StsService(_conf); sts.Grant = new ResourceOwnerGrantV2(_conf); return(sts); }); sc.AddSingleton <IHostedService, Daemon>(); sc.AddQuartz(jobs => { jobs.SchedulerId = Guid.NewGuid().ToString(); jobs.UseMicrosoftDependencyInjectionJobFactory(options => { options.AllowDefaultConstructor = false; }); jobs.UseSimpleTypeLoader(); jobs.UseInMemoryStore(); jobs.UseDefaultThreadPool(); if (bool.Parse(_conf["Jobs:MOTDDownloadJob:Enable"])) { var motdPullJobKey = new JobKey(JobType.MOTDDownloadJob.ToString(), GroupType.Daemons.ToString()); jobs.AddJob <MOTDDownloadJob>(opt => opt .StoreDurably() .WithIdentity(motdPullJobKey) ); foreach (var cron in _conf.GetSection("Jobs:MOTDDownloadJob:Schedules").GetChildren() .Select(x => x.Value).ToList()) { jobs.AddTrigger(opt => opt .ForJob(motdPullJobKey) .StartNow() .WithCronSchedule(cron) ); } } if (bool.Parse(_conf["Jobs:MOTDUploadJob:Enable"])) { var motdPushJobKey = new JobKey(JobType.MOTDUploadJob.ToString(), GroupType.Daemons.ToString()); jobs.AddJob <MOTDUploadJob>(opt => opt .StoreDurably() .WithIdentity(motdPushJobKey) ); foreach (var cron in _conf.GetSection("Jobs:MOTDUploadJob:Schedules").GetChildren() .Select(x => x.Value).ToList()) { jobs.AddTrigger(opt => opt .ForJob(motdPushJobKey) .StartNow() .WithCronSchedule(cron) ); } } }); sc.AddQuartzServer(opt => { opt.WaitForJobsToComplete = true; }); });
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHsts(options => { options.Preload = true; options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(365); }); services.AddCors(options => { options.AddPolicy("default", policy => { policy.WithOrigins(Environment.GetEnvironmentVariable("ALLOW_ORIGINS")?.Split(" ")) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddMvc(); services.AddIdentityServer(x => x.IssuerUri = Environment.GetEnvironmentVariable("ISSUER_URI")) .AddMongoRepository() .AddClients() .AddIdentityApiResources() .AddPersistedGrants() .AddProfileService <ProfileService>(); services.AddSingleton(new CertificatesGenerator(Configuration)); services.AddTransient <IResourceOwnerPasswordValidator, CustomResourceOwnerPasswordValidator>(); services.AddTransient <IProfileService, ProfileService>(); services.AddTransient <IPersistedGrantStore, CustomPersistedGrantStore>(); services.AddTransient <ISigningCredentialStore, CustomSigningCredentialStore>(); services.AddTransient <IValidationKeysStore, CustomValidationKeysStore>(); services.AddSingleton <ICorsPolicyService, CustomCorsPolicyService>(); services.AddSingleton <IHostedService, CertificatesBackgroundWorker>(); services.AddSingleton <IHostedService, PersistedGrantBackgroundWorker>(); var stsService = new StsService(); var mailService = new MailService(stsService); services.AddSingleton <IStsService>(stsService); services.AddSingleton <IMailService>(mailService); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKeyResolver = (token, securityToken, kid, parameters) => { var keys = new List <SecurityKey>(); try { var client = new HttpClient(); var disco = JsonConvert.DeserializeObject <JsonWebKeySet>( client.GetAsync($"{Environment.GetEnvironmentVariable("STS_API_URL")}/.well-known/openid-configuration/jwks") .Result.Content.ReadAsStringAsync().Result ); foreach (var webKey in disco.Keys) { var e = Base64Url.Decode(webKey.E); var n = Base64Url.Decode(webKey.N); var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = webKey.Kid }; keys.Add(key); } return(keys); } catch (Exception e) { Console.WriteLine(e); } return(keys); }, ValidIssuers = Environment.GetEnvironmentVariable("ISSUERS")?.Split(","), ValidAudiences = Environment.GetEnvironmentVariable("AUDIENCE")?.Split(","), ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = tokenValidationParameters; options.SaveToken = true; }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build(); }); services.AddMvc(options => options.EnableEndpointRouting = false); }
public MainViewModel() { IStsService stsService = new StsService(DependencyService.Get <IBrowser>()); StsList = new ObservableCollection <KeyValuePair <string, string> >(stsService.GetStsList()); SelectedSts = StsList[0]; IsAuthenticated = false; GetDiscoCommand = new Command(async() => { ResetOutput(); var disco = await stsService.GetDiscoAsync(); if (disco.IsError) { DisplayOutput(disco.Error); } else { DisplayOutput(disco); } }); GetOpenIdConfigurationCommand = new Command(async() => { ResetOutput(); var opendIdConfig = await stsService.GetOpenIdConfigurationAsync(); DisplayOutput(opendIdConfig); }); LoginCommand = new Command(async() => { ResetOutput(); var loginResult = await stsService.Login(); if (loginResult.IsError) { DisplayOutput(loginResult.Error); } else { IsAuthenticated = true; var sb = new StringBuilder(128); foreach (var claim in loginResult.User.Claims) { sb.AppendFormat("{0}: {1}\n", claim.Type, claim.Value); } sb.AppendFormat("\n{0}: {1}\n", "refresh token", loginResult?.RefreshToken ?? "none"); sb.AppendFormat("\n{0}: {1}\n", "access token", loginResult.AccessToken); DisplayOutput(sb.ToString()); } }); LogoutCommand = new Command(async() => { ResetOutput(); var logoutResult = await stsService.Logout(); if (logoutResult.IsError) { DisplayOutput(logoutResult.Error); } else { IsAuthenticated = false; } }); CallApiCommand = new Command(async() => { ResetOutput(); var result = await stsService.CallApiAsync("api/test"); DisplayOutput(result); }); }