Ejemplo n.º 1
0
        private Saml2pAuthenticationOptions BuildSamlOptions(SamlConfig config, SpOptions spOptions, IdpOptions idpOptions)
        {
            return(new Saml2pAuthenticationOptions
            {
                Licensee = "Demo",
                LicenseKey = "eyJTb2xkRm9yIjowLjAsIktleVByZXNldCI6NiwiU2F2ZUtleSI6ZmFsc2UsIkxlZ2FjeUtleSI6ZmFsc2UsImF1dGgiOiJERU1PIiwiZXhwIjoiMjAxOS0wOS0xMlQwMTowMDowMS4wODkwNTkzKzAxOjAwIiwiaWF0IjoiMjAxOS0wOC0xM1QwMDowMDowMS4wMDAwNTkzIiwib3JnIjoiREVNTyIsImF1ZCI6Mn0=.aIIw1/atlaiBci5zSxPIhdinI7tEmBZYK3Xuhe19a5twDeSzRm/i57gWpMMu/2x8O40nfAi9yk2Gbpadzv8RpOxaF5+OnnIcg4yevKLipJKZJ9bBDDC78Yl/nkhM6N65e18haUmgO/l8EYeRpYNTBE7dNGK2wZJAyqDpWpBYQ8tbCvfjchj5GGqudqFT/YLNuHn1y0Ps7mP4rh4V5G7TyIaY9QfW3ZMGJGtOQyjvTzlc02IZrw6idhRpNNazMqZAFnUKUV+bR//jyx1uBkz1H+hF0eslQt9Wt9yse3JAZi/D4oUTFyPOfzzhGkW2ceftX8tmYEWE/lPjQ3+xonKX+XNxJEXjib6d6GkTJpALpBniXS6XIKDnDV2h0Bs14lMA+2ddEDBMWVid4ubdUBZBkQLKWfZkPACUd6aBfx001v3QE2YQ9yxzdq0EAWnvEV5EE3NR4sLaNNuYxxMSoBs8ZRovhcT7Yo+o6skNu1cVvGVjOl+YMURdQgc7dPU+NxNG4oekEyW+i9N3RidvZeM1xz8dQipBMCMrrOymLV5hT32N9Y/XX4yC26zbuc5aYoaQKNqF7ZVfbrOa2H4G/Jr3pYj3EWRWfy2xlLDbUSzjcJ4ut2OZFHs5ql2Ut9y/LQ8yB3Impur6h8TpwbziWza/z2j2Gmj3rwKbN0vO2zYQJv4=",
                IdentityProviderOptions = idpOptions,
                ServiceProviderOptions = spOptions,

                //SaveTokens = true,
                NameIdClaimType = "sub",
                CallbackPath = $"/signin-saml-{config.TenantId}",
                SignInScheme = "idsrv.external",
                ClaimsIssuer = idpOptions.EntityId,
            });
        }
Ejemplo n.º 2
0
        public SuomiFiIdentificationClientTests()
        {
            var cookieStorage = new InMemoryEncryptedCookieStorage();

            samlConfig = new SamlConfig {
                Saml2SSOUrl                   = "https://testi.apro.tunnistus.fi/idp/profile/SAML2/Redirect/SSO",
                Saml2SLOUrl                   = "https://testi.apro.tunnistus.fi/idp/profile/SAML2/Redirect/SLO",
                Saml2IdpEntityId              = "https://testi.apro.tunnistus.fi/idp1",
                Saml2EntityId                 = "https://localhost/SAML/2SP",
                Saml2Certificate              = "localhost.pfx",
                Saml2IdpCertificate           = "apro-test.cer",
                Saml2CertificateStoreLocation = StoreLocation.CurrentUser
            };
            var store = new CertificateGeneratorStore();

            client = new SuomiFiIdentificationClient(samlConfig, new AuthStateAccessor(cookieStorage), new RsaShaCrypto(samlConfig, store));
        }
Ejemplo n.º 3
0
        public IActionResult AddSamlConfig(SMLConfig cfg, string tenantId)
        {
            var tenant = _repo.GetTenantById(tenantId);

            if (tenant.Protocol.Equals("saml"))
            {
                var samlcfg = new SamlConfig
                {
                    IdpEntityId           = cfg.IdpEntityId,
                    IdpSigningCertificate = cfg.IdpSigningCertificate,
                    SingleLogoutEndpoint  = cfg.SLOEndpoint,
                    SingleSignOnEndpoint  = cfg.SSOEndpoint,
                    Tenant = tenant
                };

                _repo.AddSamlConfig(samlcfg);
            }
            return(Ok());
        }
Ejemplo n.º 4
0
 public CertificateStore(SamlConfig config)
 {
     this.config = config;
 }
Ejemplo n.º 5
0
 public RsaShaCrypto(SamlConfig config, ICertificateStore certificateStore)
 {
     this.config           = config;
     this.certificateStore = certificateStore;
 }
Ejemplo n.º 6
0
 internal void AddSamlConfig(SamlConfig samlcfg)
 {
     _dbContext.Add(samlcfg);
     _dbContext.SaveChanges();
 }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Services
            services.AddScoped(typeof(IAsyncRepository <>), typeof(Repository <>));
            services.AddScoped(typeof(IDataTableService <,>), typeof(DataTableService <,>));
            services.AddScoped <IDashboardService, DashboardService>();
            services.AddScoped <IEmployeeService, EmployeeService>();
            services.AddScoped <IHardwareVaultService, HardwareVaultService>();
            services.AddScoped <IHardwareVaultTaskService, HardwareVaultTaskService>();
            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <IWorkstationService, WorkstationService>();
            services.AddScoped <IWorkstationAuditService, WorkstationAuditService>();
            services.AddScoped <ISharedAccountService, SharedAccountService>();
            services.AddScoped <ITemplateService, TemplateService>();
            services.AddScoped <IApplicationUserService, ApplicationUserService>();
            services.AddScoped <IOrgStructureService, OrgStructureService>();
            services.AddScoped <IRemoteWorkstationConnectionsService, RemoteWorkstationConnectionsService>();
            services.AddScoped <IRemoteDeviceConnectionsService, RemoteDeviceConnectionsService>();
            services.AddScoped <IRemoteTaskService, RemoteTaskService>();
            services.AddScoped <IEmailSenderService, EmailSenderService>();
            services.AddScoped <ILicenseService, LicenseService>();
            services.AddScoped <IAppSettingsService, AppSettingsService>();
            services.AddScoped <IToastService, ToastService>();
            services.AddScoped <IModalDialogService, ModalDialogService>();
            services.AddScoped <IGroupService, GroupService>();
            services.AddScoped <ILdapService, LdapService>();
            services.AddScoped <ISoftwareVaultService, SoftwareVaultService>();
            services.AddScoped <IBreadcrumbsService, BreadcrumbsService>();
            services.AddScoped <IFido2Service, Fido2Service>();
            services.AddScoped <IIdentityApiClient, IdentityApiClient>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton <IDataProtectionService, DataProtectionService>();
            services.AddSingleton <ISynchronizationService, SynchronizationService>();

            services.AddHostedService <RemoveLogsHostedService>();
            services.AddHostedService <LicenseHostedService>();
            services.AddHostedService <ActiveDirectoryHostedService>();

            services.AddHttpClient();
            services.AddHttpClient("HES").ConfigurePrimaryHttpMessageHandler(() =>
            {
                return(new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                });
            });
            services.AddSignalR();
            services.AddMemoryCache();

            // Cookie
            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.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan  = TimeSpan.FromDays(14);
                options.LoginPath       = "/login";
                options.LogoutPath      = "/Account/Logout";
                options.Cookie          = new CookieBuilder
                {
                    IsEssential = true // required for auth to work without explicit user consent; adjust to suit your privacy policy
                };
            });

            // Dismiss strong password
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 3;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireNonAlphanumeric = false;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;
            });

            services.Configure <Fido2Configuration>(Configuration.GetSection("Fido2"));

            // Database
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                                                                          ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection")),
                                                                          o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery)));

            // Identity
            services.AddIdentity <ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <RegisterSecurityKeyTokenProvider <ApplicationUser> >(RegisterSecurityKeyTokenConstants.TokenName);

            // IDP
            if (Saml2pEnabled)
            {
                services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents       = true;
                    options.Events.RaiseFailureEvents     = true;
                    options.Events.RaiseSuccessEvents     = true;
                    options.Events.RaiseInformationEvents = true;
                    options.UserInteraction.LoginUrl      = "/sso";
                    options.UserInteraction.LogoutUrl     = "/slo";
                })
                .AddAspNetIdentity <ApplicationUser>()
                .AddInMemoryIdentityResources(SamlConfig.GetIdentityResources())
                .AddInMemoryApiResources(SamlConfig.GetApis())
                .AddInMemoryClients(SamlConfig.GetClients(Configuration))
                .AddSigningCredential(SamlConfig.GetCertificate(Configuration))
                .AddSamlPlugin(options =>
                {
                    options.Licensee   = Configuration.GetValue <string>("SAML2P:LicenseName");
                    options.LicenseKey = Configuration.GetValue <string>("SAML2P:LicenseKey");
                    options.WantAuthenticationRequestsSigned = false;
                    options.UseLegacyRsaEncryption           = false;
                })
                .AddInMemoryServiceProviders(SamlConfig.GetServiceProviders(Configuration))
                .Services.Configure <CookieAuthenticationOptions>(IdentityServerConstants.DefaultCookieAuthenticationScheme, cookie => { cookie.Cookie.Name = "idsrv.idp"; });
            }

            // Auth policy
            services.AddAuthorization(config =>
            {
                config.AddPolicy("RequireAdministratorRole",
                                 policy => policy.RequireRole("Administrator"));
                config.AddPolicy("RequireUserRole",
                                 policy => policy.RequireRole("User"));
            });

            // Override OnRedirectToLogin via API
            services.ConfigureApplicationCookie(config =>
            {
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return(Task.CompletedTask);
                    },
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            // Mvc
            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage", "RequireAdministratorRole");
            })
            .AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddControllers();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Localization Options
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("it"),
                    new CultureInfo("uk-UA"),
                    new CultureInfo("uk"),
                    new CultureInfo("ru-RU"),
                    new CultureInfo("ru-UA"),
                    new CultureInfo("ru"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de")
                };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });

            // Register the Swagger generator
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "HES API", Version = "v1"
                });
            });
        }