Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // var logger = _loggerFactory.CreateLogger<Startup>();

            // if (_env.IsDevelopment()) {
            // // Development service configuration
            // logger.LogInformation("Development environment");
            // }
            // else    {
            // // Non-development service configuration
            // logger.LogInformation($"Environment: {_env.EnvironmentName}");
            // }

            var oktaMvcOptions = new OktaMvcOptions()
            {
                OktaDomain   = _config.GetSection("Okta").GetValue <string>("OktaDomain"),
                ClientId     = _config.GetSection("Okta").GetValue <string>("ClientId"),
                ClientSecret = _config.GetSection("Okta").GetValue <string>("ClientSecret"),
                Scope        = new List <string> {
                    "openid", "profile", "email"
                },
            };

            services.AddSingleton <IHostingEnvironment> (_env);

            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.AddDbContext <ge_DbContext>(options =>
                                                 options.UseSqlServer(_config.GetConnectionString("ge_DbContext")));
            // .EnableSensitiveDataLogging());

            services.AddDefaultIdentity <ge_user>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ge_DbContext>();
            services.Configure <ags_config>(_config.GetSection("ags_config"));
            services.Configure <smpt_config>(_config.GetSection("smpt_config"));
            services.Configure <ge_config>(_config.GetSection("ge_config"));
            services.Configure <FormOptions>(x => {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });

            services.AddScoped <IAuthorizationHandler, ge_repositoryIsOwnerAuthorizationHandler>();
            services.AddScoped <IAuthorizationHandler, ge_repositoryAuthorizationHandler>();
            services.AddScoped <IAuthorizationHandler, ge_repositoryGroupAuthorizationHandler>();
            services.AddScoped <IAuthorizationHandler, ge_repositoryProjectAuthorizationHandler>();
            services.AddScoped <IAuthorizationHandler, ge_repositoryDataAuthorizationHandler>();

            services.AddSingleton <IAuthorizationHandler, ge_repositoryAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, ge_repositoryManagerAuthorizationHandler>();

            services.AddSingleton <IEmailSender, EmailSender>();


            // https://stackoverflow.com/questions/53973854/how-to-get-session-in-asp-net-core-2-1-when-i-have-aspnetcore-session-cookie
            // services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
            })

            .AddCookie(options =>
            {
                options.LoginPath = new PathString("/Account/SignIn");
            })
            .AddOktaMvc(oktaMvcOptions);

            // https://stackoverflow.com/questions/53973854/how-to-get-session-in-asp-net-core-2-1-when-i-have-aspnetcore-session-cookie

            // services.Configure<CookiePolicyOptions>(options =>
            //                     {
            //                 options.CheckConsentNeeded = context => true;
            //                 options.MinimumSameSitePolicy = SameSiteMode.None;
            //                     });

            // services.AddDistributedMemoryCache();

            // services.AddSession(options =>
            //                     {
            //                         // Set a short timeout for easy testing.
            //                         options.IdleTimeout = TimeSpan.FromSeconds(10);
            //                         options.Cookie.HttpOnly = true;
            //                     });

            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddTransient <IDataService, DataService>();
            services.AddTransient <IProjectService, ProjectService>();
            services.AddTransient <IGroupService, GroupService>();
            services.AddTransient <ITransformService, TransformService>();
            services.AddTransient <IUserOpsService, UserOpsService>();

            services.AddTransient <IDataLoggerFileService, DataLoggerFileService>();

            services.AddTransient <IDataAGSService, DataAGSService>();
            services.AddTransient <IDataKMLService, DataKMLService>();
            services.AddTransient <IDataTableFileService, DataTableFileService>();

            // groundwater db connections
            services.AddTransient <ILoggerFileService, LoggerFileService>();

            // gINT Database connections
            services.AddTransient <IMONDLogService, MONDLogService>();

            // Esri Feature Server connections
            services.AddTransient <ILTCEsriService, LTCEsriService>();


            // services.AddSwaggerGen(c =>
            // {
            //     c.SwaggerDoc("v1", new OpenApiInfo { Title = "ge_repository.api", Version = "v1" });
            // });

            // services.AddAutoMapper(typeof(Startup));

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddXmlSerializerFormatters()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddMvcOptions(m => m.ModelMetadataDetailsProviders.Add(new AGSMetadataProvider()));
            //.AddRazorPagesOptions(options =>
            // {
            // options.Conventions.AddPageRoute("/Pages/Index", "");
            // });
        }
        public void SetOpenIdConnectsOptionsCorrectly(bool getClaimsFromUserInfoEndpoint)
        {
            var mockTokenValidatedEvent       = Substitute.For <Func <TokenValidatedContext, Task> >();
            var mockUserInfoReceivedEvent     = Substitute.For <Func <UserInformationReceivedContext, Task> >();
            var mockOktaExceptionEvent        = Substitute.For <Func <RemoteFailureContext, Task> >();
            var mockAuthenticationFailedEvent = Substitute.For <Func <AuthenticationFailedContext, Task> >();

            var oktaMvcOptions = new OktaMvcOptions
            {
                PostLogoutRedirectUri = "http://foo.postlogout.com",
                AuthorizationServerId = "bar",
                ClientId     = "foo",
                ClientSecret = "baz",
                OktaDomain   = "http://myoktadomain.com",
                GetClaimsFromUserInfoEndpoint = getClaimsFromUserInfoEndpoint,
                CallbackPath = "/somecallbackpath",
                Scope        = new List <string> {
                    "openid", "profile", "email"
                },
                OnTokenValidated          = mockTokenValidatedEvent,
                OnUserInformationReceived = mockUserInfoReceivedEvent,
                OnAuthenticationFailed    = mockAuthenticationFailedEvent,
                OnOktaApiFailure          = mockOktaExceptionEvent,
            };

            var events = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = null
            };

            var oidcOptions = new OpenIdConnectOptions();

            OpenIdConnectOptionsHelper.ConfigureOpenIdConnectOptions(oktaMvcOptions, events, oidcOptions);

            oidcOptions.ClientId.Should().Be(oktaMvcOptions.ClientId);
            oidcOptions.ClientSecret.Should().Be(oktaMvcOptions.ClientSecret);
            oidcOptions.SignedOutRedirectUri.Should().Be(oktaMvcOptions.PostLogoutRedirectUri);
            oidcOptions.GetClaimsFromUserInfoEndpoint.Should().Be(oktaMvcOptions.GetClaimsFromUserInfoEndpoint);
            oidcOptions.CallbackPath.Value.Should().Be(oktaMvcOptions.CallbackPath);

            var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);

            oidcOptions.Authority.Should().Be(issuer);

            oidcOptions.Scope.ToList().Should().BeEquivalentTo(oktaMvcOptions.Scope);
            oidcOptions.CallbackPath.Value.Should().Be(oktaMvcOptions.CallbackPath);
            oidcOptions.Events.OnRedirectToIdentityProvider.Should().BeNull();

            // Check the event was call once with a null parameter
            oidcOptions.Events.OnTokenValidated(null);
            mockTokenValidatedEvent.Received(1).Invoke(null);
            oidcOptions.Events.OnAuthenticationFailed(null);
            mockAuthenticationFailedEvent.Received(1).Invoke(null);
            oidcOptions.Events.OnRemoteFailure(null);
            mockOktaExceptionEvent.Received(1).Invoke(null);

            // UserInfo event is mapped only when GetClaimsFromUserInfoEndpoint = true
            if (oidcOptions.GetClaimsFromUserInfoEndpoint)
            {
                // Check the event was call once with a null parameter
                oidcOptions.Events.OnUserInformationReceived(null);
                mockUserInfoReceivedEvent.Received(1).Invoke(null);
            }
        }