// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .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); } services.AddResponseCaching(); services.AddLogging(); //This provides JwtBearer support for Authorize attribute/header services.AddJwtAuthorization(cert); RegisterDatabaseServices(services); }
// 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); RegisterRefitInterfaces(services); services.AddTypeConverters(GetType().Assembly); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddGladMMOCORS(); 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); RegisterRefitInterfaces(services); RegisterAzureServiceQueue(services); services.AddCommonLoggingAdapter(); services.AddHostedService <ExpiredZoneServerCleanupJob>(); services.AddSingleton <TimedJobConfig <ExpiredZoneServerCleanupJob> >(new TimedJobConfig <ExpiredZoneServerCleanupJob>(TimeSpan.FromMinutes(11))); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //https://stackoverflow.com/questions/4926676/mono-https-webrequest-fails-with-the-authentication-or-decryption-has-failed ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.CheckCertificateRevocationList = false; services.Configure <IISOptions>(options => { 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(); //TODO: Renable services.AddDbContext <GuardiansZoneAuthenticationDbContext>(options => { //F**k configuration, I'm sick of it and we can't check it into source control //so we're using enviroment variables for sensitive deployment specific values. #if AZURE_RELEASE || AZURE_DEBUG try { options.UseMySql(Environment.GetEnvironmentVariable(GladMMOServiceConstants.AUTHENTICATION_DATABASE_CONNECTION_STRING_ENV_VAR_PATH)); } catch (Exception e) { throw new InvalidOperationException($"Failed to register Authentication Database. Make sure Env Variable path: {GladMMOServiceConstants.AUTHENTICATION_DATABASE_CONNECTION_STRING_ENV_VAR_PATH} is correctly configured.", e); } #else options.UseMySql(authOptions.Value.AuthenticationDatabaseString); #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 <ZoneServerApplicationUser, 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 <GuardiansZoneAuthenticationDbContext>() .AddDefaultTokenProviders(); services.AddOpenIddict <int>(options => { // Register the Entity Framework stores. options.AddEntityFrameworkCoreStores <GuardiansZoneAuthenticationDbContext>(); // 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); } options.SetIssuer(new Uri(@"https://zoneauth.vrguardians.net")); options.RequireClientIdentification(); }); #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; }); //TODO: Don't hardcode cert 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.AddJustAuthorization(cert); }
/// <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, bool shouldUseDefaultUrlIfNoneProvided = true) { Parser.Default.ParseArguments <DefaultWebHostingArgumentsModel>(args) .WithParsed(model => { //If https is enabled then a certifcate should be available for loading. builder.UseKestrel(options => { //Get the port if (model.isCustomUrlDefined) { int port = 5000; int.TryParse(model.Url.Split(':').Last(), out port); //Idea here is that if they specified the port, then we can actually use it as the HTTPS port setting. if (model.isHttpsEnabled) { builder.UseSetting("https_port", port.ToString()); } //Remov http string ip = model.Url.Replace("http://", ""); ip = ip.Replace("https://", ""); if (ip.Contains(':')) { ip = ip.Split(':').First(); } var modelUrl = model.isHttpsEnabled ? model.Url .ToLower() .Replace(@"http://", @"https://") : model.Url; //TODO: This won't actually work, it's not an IP. if (model.isHttpsEnabled) { builder.UseSetting("https_endpoint", modelUrl); } builder.UseUrls(modelUrl); } else if (shouldUseDefaultUrlIfNoneProvided) { string prefix = model.isHttpsEnabled ? @"https://" : @"http://"; builder.UseUrls($@"{prefix}localhost:5000"); } //.UseSetting("https_port", "443") if (model.isHttpsEnabled) { options.Listen(new IPEndPoint(IPAddress.Parse(builder.GetSetting("https_endpoint")), Int32.Parse(builder.GetSetting("https_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); } }); } //Check if we have an http setting set string potentialHttpValue = builder.GetSetting("http_endpoint"); if (!String.IsNullOrWhiteSpace(potentialHttpValue)) { options.Listen(new IPEndPoint(IPAddress.Parse(builder.GetSetting("http_endpoint")), Int32.Parse(builder.GetSetting("http_port")))); } }); }); return(builder); }
// 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))); options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(NetworkEntityGuid))); options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(CreatureInstanceModel))); options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(GameObjectInstanceModel))); options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(PlayerSpawnPointInstanceModel))); }) .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); //TODO: Simplify avatar/world content repos with base repo. //Adds and registers S3 service for URLBuilding and communication/credentials and etc //services.AddS3Service(Configuration); //World services.AddTransient <IWorldEntryRepository, DatabaseBackedWorldEntryRepository>(); services.AddTransient <ICustomContentRepository <WorldEntryModel> >(provider => provider.GetRequiredService <IWorldEntryRepository>()); //Avatar services.AddTransient <IAvatarEntryRepository, DatabaseBackedAvatarEntryRepository>(); services.AddTransient <ICustomContentRepository <AvatarEntryModel> >(provider => provider.GetRequiredService <IAvatarEntryRepository>()); //Creature services.AddTransient <ICustomContentRepository <CreatureModelEntryModel>, DatabaseBackedCreatureModelEntryRepository>(); services.AddTransient <ICreatureTemplateRepository, DatabaseBackedCreatureTemplateEntryRepository>(); services.AddTransient <ICreatureEntryRepository, DatabaseBackedCreatureEntryRepository>(); //GameObjects services.AddTransient <ICustomContentRepository <GameObjectModelEntryModel>, DatabaseBackedGameObjectModelEntryRepository>(); services.AddTransient <IGameObjectTemplateRepository, DatabaseBackedGameObjectTemplateEntryRepository>(); services.AddTransient <IGameObjectEntryRepository, DatabaseBackedGameObjectEntryRepository>(); services.AddTransient <IWorldTeleporterGameObjectEntryRepository, DatabaseBackedWorldTeleporterEntryRepository>(); services.AddTransient <IAvatarPedestalGameObjectEntryRepository, DatabaseBackedAvatarPedestalEntryRepository>(); //Spells services.AddTransient <ISpellEntryRepository, DatabaseBackedSpellEntryModelRepository>(); services.AddTransient <ILevelLearnedSpellRepository, DatabaseBackedLevelLearnedSpellRepository>(); //Player //DatabaseBackedPlayerSpawnPointEntryRepository : IPlayerSpawnPointEntryRepository services.AddTransient <IPlayerSpawnPointEntryRepository, DatabaseBackedPlayerSpawnPointEntryRepository>(); //Content //DatabaseBackedContentIconEntryRepository : BaseGenericBackedDatabaseRepository<ContentDatabaseContext, int, ContentIconEntryModel>, IContentIconEntryModelRepository services.AddTransient <IContentIconEntryModelRepository, DatabaseBackedContentIconEntryRepository>(); services.AddTransient <IContentDownloadAuthroizationValidator, UnimplementedContentDownloadAuthorizationValidator>(); //AZURE_STORAGE_CONNECTIONSTRING string ConnectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTIONSTRING"); if (String.IsNullOrWhiteSpace(ConnectionString)) { throw new InvalidOperationException($"Failed to load AZURE_STORAGE_CONNECTIONSTRING."); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString); services.AddScoped(p => storageAccount.CreateCloudBlobClient()); services.AddTransient <IStorageUrlBuilder, AzureBlobStorageURLBuilder>(); //Register all the type converters in the assembly services.AddTypeConverters(GetType().Assembly); //DefaultCreatureEntryModelFactory : IFactoryCreatable<CreatureEntryModel, WorldInstanceableEntryModelCreationContext> services.AddTransient <IFactoryCreatable <CreatureEntryModel, WorldInstanceableEntryModelCreationContext>, DefaultCreatureEntryModelFactory>(); //DefaultGameObjectEntryModelFactory : IFactoryCreatable<GameObjectEntryModel, WorldInstanceableEntryModelCreationContext> services.AddTransient <IFactoryCreatable <GameObjectEntryModel, WorldInstanceableEntryModelCreationContext>, DefaultGameObjectEntryModelFactory>(); //DefaultPlayerSpawnPointEntryModelFactory : IFactoryCreatable<PlayerSpawnPointEntryModel, WorldInstanceableEntryModelCreationContext> services.AddTransient <IFactoryCreatable <PlayerSpawnPointEntryModel, WorldInstanceableEntryModelCreationContext>, DefaultPlayerSpawnPointEntryModelFactory>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //https://stackoverflow.com/questions/4926676/mono-https-webrequest-fails-with-the-authentication-or-decryption-has-failed ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.CheckCertificateRevocationList = false; 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(); ISignalRServerBuilder signalRBuilder = services.AddSignalR(options => { }).AddJsonProtocol(); //TODO: Handle failure. //This adds the SignalR rerouting to the specified SignalR backplane. #if AZURE_RELEASE || AZURE_DEBUG signalRBuilder.AddAzureSignalR(Environment.GetEnvironmentVariable(GladMMOServiceConstants.AZURE_SIGNALR_CONNECTION_STRING_ENV_VAR_PATH)); #endif services.AddSingleton <IUserIdProvider, SignalRPlayerCharacterUserIdProvider>(); //TODO: Support release/prod service query. #if AZURE_RELEASE || AZURE_DEBUG services.AddSingleton <IServiceDiscoveryService>(provider => RestService.For <IServiceDiscoveryService>("https://test-guardians-servicediscovery.azurewebsites.net")); #else services.AddSingleton <IServiceDiscoveryService>(provider => RestService.For <IServiceDiscoveryService>("http://72.190.177.214:5000")); #endif services.AddSingleton <IReadonlyAuthTokenRepository, SocialServiceAuthTokenRepository>(); services.AddSingleton <IAuthenticationService, AsyncEndpointAuthenticationService>(provider => { return(new AsyncEndpointAuthenticationService(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), "Authentication"), new RefitSettings() { HttpMessageHandlerFactory = () => new BypassHttpsValidationHandler() })); }); services.AddSingleton <ISocialServiceToGameServiceClient, AsyncEndpointISocialServiceToGameServiceClient>(provider => { IReadonlyAuthTokenRepository repository = provider.GetService <IReadonlyAuthTokenRepository>(); return(new AsyncEndpointISocialServiceToGameServiceClient(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), "GameServer"), new RefitSettings() { HttpMessageHandlerFactory = () => new AuthenticatedHttpClientHandler(repository) })); }); services.AddSingleton <INameQueryService>(provider => { IReadonlyAuthTokenRepository repository = provider.GetService <IReadonlyAuthTokenRepository>(); return(new AsyncEndpointNameQueryService(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), "NameQuery"), new RefitSettings() { HttpMessageHandlerFactory = () => new AuthenticatedHttpClientHandler(repository) })); }); services.AddSingleton <ISocialService>(provider => { IReadonlyAuthTokenRepository repository = provider.GetService <IReadonlyAuthTokenRepository>(); return(new AsyncSocialServiceClient(QueryForRemoteServiceEndpoint(provider.GetService <IServiceDiscoveryService>(), GladMMONetworkConstants.SOCIAL_SERVICE_NAME), new RefitSettings() { HttpMessageHandlerFactory = () => new AuthenticatedHttpClientHandler(repository) })); }); //This is for Hub connection event listeners services.AddSingleton <IOnHubConnectionEventListener, CharacterZoneOnHubConnectionEventListener>(); services.AddSingleton <IOnHubConnectionEventListener, CharacterGuildOnHubConnectionEventListener>(); //SocialSignalRMessageRouter<TRemoteClientHubInterfaceType> : ISocialModelMessageRouter<TRemoteClientHubInterfaceType> services.AddSingleton <ISocialModelMessageRouter <IRemoteSocialHubClient>, SocialSignalRMessageRouter <IRemoteSocialHubClient> >(); services.AddSingleton <ISocialModelPayloadHandler <IRemoteSocialHubClient>, TestSocialModelHandler>(); services.AddSingleton <ISocialModelPayloadHandler <IRemoteSocialHubClient>, GuildMemberInviteRequestModelHandler>(); services.AddSingleton <ISocialModelPayloadHandler <IRemoteSocialHubClient>, PendingGuildInviteResultHandler>(); RegisterDatabaseServices(services); }