// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { //This prevents ASP Core from trying to validate Vector3's children, which contain Vector3 (because Unity3D thanks) //so it will cause stack overflows. This will avoid it. options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Vector3))); }) .RegisterHealthCheckController(); RegisterDatabaseServices(services); X509Certificate2 cert = null; string certPath = "Certs/TestCert.pfx"; try { cert = X509Certificate2Loader.Create(certPath).Load(); } catch (Exception e) { throw new System.InvalidOperationException($"Failed to load {nameof(X509Certificate2)} from Path: {certPath} \n\n StackTrace: {e.StackTrace}", e); } services.AddResponseCaching(); services.AddLogging(); //This provides JwtBearer support for Authorize attribute/header services.AddJwtAuthorization(cert); //Adds and registers S3 service for URLBuilding and communication/credentials and etc services.AddS3Service(Configuration); services.AddTransient <IWorldEntryRepository, DatabaseBackedWorldEntryRepository>(); services.AddTransient <IAvatarEntryRepository, DatabaseBackedAvatarEntryRepository>(); services.AddTransient <IContentDownloadAuthroizationValidator, UnimplementedContentDownloadAuthorizationValidator>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { //This prevents ASP Core from trying to validate Vector3's children, which contain Vector3 (because Unity3D thanks) //so it will cause stack overflows. This will avoid it. options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Vector3))); }) .RegisterHealthCheckController(); RegisterDatabaseServices(services); X509Certificate2 cert = null; string certPath = "Certs/TestCert.pfx"; try { cert = X509Certificate2Loader.Create(certPath).Load(); } catch (Exception e) { throw new System.InvalidOperationException($"Failed to load {nameof(X509Certificate2)} from Path: {certPath} \n\n StackTrace: {e.StackTrace}", e); } services.AddResponseCaching(); services.AddLogging(); //This provides JwtBearer support for Authorize attribute/header services.AddJwtAuthorization(cert); services.AddSingleton <IZoneInstanceWorkQueue, LocalInMemoryZoneInstanceWorkQueue>(provider => { //TODO: This is for testing purposes, we want and have the request to boot up at map 1 as an instance. return(new LocalInMemoryZoneInstanceWorkQueue(new ZoneInstanceWorkEntry(1), new ZoneInstanceWorkEntry(1))); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { //This prevents ASP Core from trying to validate Vector3's children, which contain Vector3 (because Unity3D thanks) //so it will cause stack overflows. This will avoid it. //options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Vector3))); }) .RegisterHealthCheckController(); X509Certificate2 cert = null; string certPath = "Certs/TestCert.pfx"; try { cert = X509Certificate2Loader.Create(certPath).Load(); } catch (Exception e) { throw new System.InvalidOperationException($"Failed to load {nameof(X509Certificate2)} from Path: {certPath} \n\n StackTrace: {e.StackTrace}", e); } //This provides JwtBearer support for Authorize attribute/header services.AddJwtAuthorization(cert); services.AddResponseCaching(); services.AddSignalR(options => { }).AddJsonProtocol(); services.AddSingleton <IUserIdProvider, SignalRPlayerCharacterUserIdProvider>(); services.AddSingleton <IConnectionToZoneMappable, DefaultConnectionToZoneMappable>(); //Registers service discovery client. services.AddSingleton <IServiceDiscoveryService>(provider => { return(Refit.RestService.For <IServiceDiscoveryService>("http://sd.vrguardians.net:5000")); }); services.AddSingleton <IAuthenticationService, AsyncEndpointAuthenticationService>(provider => { return(new AsyncEndpointAuthenticationService(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), "Authentication"))); }); services.AddSingleton <ISocialServiceToGameServiceClient, AsyncEndpointISocialServiceToGameServiceClient>(provider => { return(new AsyncEndpointISocialServiceToGameServiceClient(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), "GameServer"), new RefitSettings() { AuthorizationHeaderValueGetter = () => GetSocialServiceAuthorizationToken(provider.GetService <IAuthenticationService>()) })); }); //This is for Hub connection event listeners services.AddSingleton <IOnHubConnectionEventListener, CharacterZoneOnHubConnectionEventListener>(); services.AddSingleton <IOnHubConnectionEventListener, CharacterGuildOnHubConnectionEventListener>(); services.AddSingleton <ZoneMessageBroadcastMessageHandler, ZoneMessageBroadcastMessageHandler>(); services.AddSingleton <GuildMessageBroadcastMessageHandler, GuildMessageBroadcastMessageHandler>(); services.AddSingleton <IFactoryCreatable <GuildChatMessageEventModel, GenericChatMessageContext <GuildChatMessageRequestModel> >, GuildChatMessageEnvelopeFactory>(); services.AddSingleton <IFactoryCreatable <ZoneChatMessageEventModel, GenericChatMessageContext <ZoneChatMessageRequestModel> >, ZoneChatMessageEnvelopeFactory>(); services.AddSingleton <IEntityDataLockingService, RefCountedEntityDataLockingService>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<IISOptions>(options => { options.ForwardClientCertificate = false; options.AutomaticAuthentication = false; }); // Add framework services. services.AddMvc() .RegisterHealthCheckController(); services.AddLogging(); services.AddOptions(); services.Configure<AuthenticationServerConfigurationModel>(GeneralConfiguration.GetSection("AuthConfig")); //We need to immediately resolve the authserver config options because we need them to regiter openiddict IOptions<AuthenticationServerConfigurationModel> authOptions = services.BuildServiceProvider() .GetService<IOptions<AuthenticationServerConfigurationModel>>(); services.AddAuthentication(); services.AddDbContext<GuardiansAuthenticationDbContext>(options => { //TODO: Setup db options //On local builds we don't want to use config. We want to default to local #if !DEBUG_LOCAL && !RELEASE_LOCAL options.UseMySql(authOptions.Value.AuthenticationDatabaseString); #else options.UseMySql("Server=72.190.177.214;Database=guardians.auth;Uid=root;Pwd=test;"); #endif options.UseOpenIddict<int>(); }); //Below is the OpenIddict registration //This is the recommended setup from the official Github: https://github.com/openiddict/openiddict-core services.AddIdentity<GuardiansApplicationUser, GuardiansApplicationRole>(options => { //These disable the ridiculous requirements that the defauly password scheme has options.Password.RequireNonAlphanumeric = false; //For some reason I can't figure out how to get the JWT middleware to spit out sub claims //so we need to map the Identity to expect nameidentifier options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject; options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role; options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name; }) .AddEntityFrameworkStores<GuardiansAuthenticationDbContext>() .AddDefaultTokenProviders(); services.AddOpenIddict<int>(options => { // Register the Entity Framework stores. options.AddEntityFrameworkCoreStores<GuardiansAuthenticationDbContext>(); //This will disable the https requirement if we're debugging or not in production/debug mode. #if DEBUG || DEBUGBUILD options.DisableHttpsRequirement(); #endif // Register the ASP.NET Core MVC binder used by OpenIddict. // Note: if you don't call this method, you won't be able to // bind OpenIdConnectRequest or OpenIdConnectResponse parameters. options.AddMvcBinders(); //This controller endpoint/action was specified in the HaloLive documentation: https://github.com/HaloLive/Documentation options.EnableTokenEndpoint(authOptions.Value.AuthenticationControllerEndpoint); // Enable the token endpoint (required to use the password flow). options.AllowPasswordFlow(); // Allow client applications to use the grant_type=password flow. options.AllowRefreshTokenFlow(); options.UseJsonWebTokens(); #warning Don't deploy this into production; we should use HTTPS. Even if it is behind IIS or HAProxy etc. options.DisableHttpsRequirement(); try { //Loads the cert from the specified path options.AddSigningCertificate(X509Certificate2Loader.Create(Path.Combine(Directory.GetCurrentDirectory(), authOptions.Value.JwtSigningX509Certificate2Path)).Load()); } catch(Exception e) { throw new InvalidOperationException($"Failed to load cert at Path: {authOptions.Value.JwtSigningX509Certificate2Path} with Root: {Directory.GetCurrentDirectory()}. Error: {e.Message} \n\n Stack: {e.StackTrace}", e); } }); #warning This is just for the test build, we don't actually want to do this services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 1; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; }); }
/// <summary> /// Configure the server host with the arguments encoded in the <see cref="args"/> mapped to /// an options instance of <see cref="DefaultWebHostingArgumentsModel"/>. /// </summary> /// <param name="builder">The web host builder.</param> /// <param name="args">The commandline args.</param> /// <returns>The provided <see cref="IWebHostBuilder"/>for fluent chaining.</returns> public static IWebHostBuilder ConfigureKestrelHostWithCommandlinArgs(this IWebHostBuilder builder, string[] args) { Parser.Default.ParseArguments <DefaultWebHostingArgumentsModel>(args) .WithParsed(model => { #if NETCOREAPP2_0 //If https is enabled then a certifcate should be available for loading. builder.UseKestrel(options => { int port = 5000; //Get the port if (model.isCustomUrlDefined) { int.TryParse(model.Url.Split(':').Last(), out port); } //Remov http string ip = model.Url.Replace("http://", ""); ip = ip.Replace("https://", ""); if (ip.Contains(':')) { ip = ip.Split(':').First(); } options.Listen(new IPEndPoint(IPAddress.Parse(ip), port), listenOptions => { if (model.isHttpsEnabled) { var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions() { //TODO: Do we need this in ASP Core 2.0? //ClientCertificateMode = ClientCertificateMode.AllowCertificate, //TODO: Mono doesn't support Tls1 or Tls2 and we have no way to config this. //Ssl3 is mostly safe and supported by Mono which means it will work in Unity3D now. SslProtocols = System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12, ServerCertificate = X509Certificate2Loader.Create(model.HttpsCertificateName).Load() }; listenOptions.UseHttps(httpsConnectionAdapterOptions); } }); //We still need this for the purposes for Features addresses //It won't conflict with the above if (model.isCustomUrlDefined) { builder.UseUrls(model.isHttpsEnabled ? model.Url .ToLower() .Replace(@"http://", @"https://") : model.Url); } else { string prefix = model.isHttpsEnabled ? @"https://" : @"http://"; builder.UseUrls($@"{prefix}localhost:5000"); } }); #else if (model.isHttpsEnabled) { builder.UseKestrel(options => { options.UseHttps(new HttpsConnectionFilterOptions() { //TODO: Mono doesn't support Tls1 or Tls2 and we have no way to config this. //Ssl3 is mostly safe and supported by Mono which means it will work in Unity3D now. SslProtocols = System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12, //Load the cert with the cert loader ServerCertificate = X509Certificate2Loader.Create(model.HttpsCertificateName).Load() }); }); } else { builder.UseKestrel(); } //TODO: Should we allow both https and non-https traffic? if (model.isCustomUrlDefined) { builder.UseUrls(model.isHttpsEnabled ? model.Url .ToLower() .Replace(@"http://", @"https://") : model.Url); } else { string prefix = model.isHttpsEnabled ? @"https://" : @"http://"; builder.UseUrls($@"{prefix}localhost:5000"); } #endif }); return(builder); }