コード例 #1
0
        /// <summary>
        /// Constructor that highlights all required fields for this object
        /// </summary>
        public Configuration(string eMandateContractId, string merchantReturnUrl, string signingCertificateFingerprint, string acquirerCertificateFingerprint, string acquirerAlternateCertificateFingerprint, string acquirerUrlDirectoryReq, string acquirerUrlTransactionReq,
                             string acquirerUrlStatusReq, bool serviceLogsEnabled, string serviceLogsLocation, ILoggerFactory loggerFactory = null, ICertificateLoader certificateLoader = null, string serviceLogsPattern = null, uint eMandateContractSubId = 0)
        {
            this.EMandateContractId                      = eMandateContractId;
            this.EMandateContractSubId                   = eMandateContractSubId;
            this.MerchantReturnUrl                       = merchantReturnUrl;
            this.SigningCertificateFingerprint           = signingCertificateFingerprint;
            this.AcquirerCertificateFingerprint          = acquirerCertificateFingerprint;
            this.AcquirerAlternateCertificateFingerprint = acquirerAlternateCertificateFingerprint;
            this.AcquirerUrlDirectoryReq                 = acquirerUrlDirectoryReq;
            this.AcquirerUrlTransactionReq               = acquirerUrlTransactionReq;
            this.AcquirerUrlStatusReq                    = acquirerUrlStatusReq;

            this.ServiceLogsEnabled  = serviceLogsEnabled;
            this.ServiceLogsLocation = serviceLogsLocation;
            this.ServiceLogsPattern  = string.IsNullOrWhiteSpace(serviceLogsPattern) ? @"%Y-%M-%D\%h%m%s.%f-%a.xml" : serviceLogsPattern;

            this.LoggerFactory = loggerFactory ?? new LoggerFactory();

            this.CertificateLoader            = certificateLoader ?? new CertificateStoreLoader();
            this.SigningCertificate           = CertificateLoader.Load(SigningCertificateFingerprint);
            this.AcquirerCertificate          = CertificateLoader.Load(AcquirerCertificateFingerprint);
            this.AcquirerAlternateCertificate = CertificateLoader.Load(AcquirerAlternateCertificateFingerprint);
        }
コード例 #2
0
        /// <summary>
        /// Creates a <see cref="RestClient"/> using a given <see cref="AuthenticationData"/>
        /// </summary>
        /// <param name="authenticationData">The data from which the instance will be created</param>
        public static RestClient CreateFrom(AuthenticationData authenticationData)
        {
            switch (authenticationData.Type)
            {
            case AuthenticationMethodProvider.AuthenticationType.SymmetricKey:
            {
                // Getting a specific module using REST with SAS token authentication
                string key        = ConfigurationUtils.GetSymmetricKeyFromFile(authenticationData.FilePath);
                string sasToken   = GenerateSaSToken(key, authenticationData.GatewayHostName, TimeSpan.FromMinutes(_sasTokenTtl));
                var    restClient = new RestClient(authenticationData.GatewayHostName, sasToken);
                return(restClient);
            }

            case AuthenticationMethodProvider.AuthenticationType.SelfSignedCertificate:
            {
                X509Certificate2 cert = CertificateLoader.Load(authenticationData.CertificateLocation.Value, authenticationData.FilePath);
                var restClient        = new RestClient(authenticationData.GatewayHostName, cert);
                return(restClient);
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(authenticationData.Type), authenticationData.Type, "Unsupported authentication type");
            }
        }
コード例 #3
0
 public void ShouldThrowOnFilePathNotSupplied()
 {
     Assert.ThrowsException <ArgumentNullException>(() => { using (var x = CertificateLoader.Load(AuthenticationMethodProvider.CertificateLocation.LocalFile, null)) { } });
 }
コード例 #4
0
            public void ShouldLoadCertificateFromStore()
            {
                X509Certificate2 certificate = CertificateLoader.Load(AuthenticationMethodProvider.CertificateLocation.Store, _tempStoreInfoPath);

                Assert.AreEqual(_expectedCertificate.Thumbprint, certificate.Thumbprint);
            }
コード例 #5
0
 public void ShouldThrowOnUnexpectedCertificateLocation()
 {
     Assert.ThrowsException <ArgumentOutOfRangeException>(() => { using (var x = CertificateLoader.Load((AuthenticationMethodProvider.CertificateLocation) int.MaxValue, string.Empty)) { } });
 }
コード例 #6
0
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine($"SettingsService version {PlatformServices.Default.Application.ApplicationVersion}");
#if DEBUG
                Console.WriteLine("Is DEBUG");
#else
                Console.WriteLine("Is RELEASE");
#endif
                var host = Host.CreateDefaultBuilder(args)
                           .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                           .UseSerilog()
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .ConfigureWebHostDefaults(hostBuilder =>
                {
                    var sertConnString = Environment.GetEnvironmentVariable("CertConnectionString");
                    if (string.IsNullOrWhiteSpace(sertConnString) || sertConnString.Length < 10)
                    {
                        hostBuilder
                        .UseKestrel()
                        .UseUrls("http://*:5000/");
                    }
                    else
                    {
                        var xcert = CertificateLoader.Load(sertConnString);
                        hostBuilder
                        .UseKestrel(x =>
                        {
                            x.Listen(IPAddress.Any, 443, listenOptions => listenOptions.UseHttps(xcert));
                            x.AddServerHeader = false;
                        })
                        .UseUrls("https://*:443/");
                    }
                    hostBuilder.UseStartup <Startup>();
                })
                           .Build();

                host.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal error:");
                Console.WriteLine(ex);

                // Lets devops to see startup error in console between restarts in the Kubernetes
                var delay = TimeSpan.FromMinutes(1);

                Console.WriteLine();
                Console.WriteLine($"Process will be terminated in {delay}. Press any key to terminate immediately.");

                Task.WhenAny(
                    Task.Delay(delay),
                    Task.Run(() =>
                {
                    Console.ReadKey(true);
                }))
                .Wait();
            }

            Console.WriteLine("Terminated");
        }
コード例 #7
0
ファイル: Startup.cs プロジェクト: Icidis/OidcTemplate
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var domainSettings = new DomainSettings();

            Configuration.GetSection(nameof(DomainSettings)).Bind(domainSettings);
            services.Configure <DomainSettings>(options => Configuration.GetSection(nameof(DomainSettings)).Bind(options));

            var appSettings = new AppSettings();

            Configuration.GetSection(nameof(AppSettings)).Bind(appSettings);

            var connectionString   = appSettings.ConnectionStrings.AuthContext;
            var migrationsAssembly = typeof(DataModule).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <IdentityContext>(o => o.UseSqlServer(connectionString,
                                                                        optionsBuilder =>
                                                                        optionsBuilder.MigrationsAssembly(typeof(DataModule).GetTypeInfo().Assembly.GetName().Name)));
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <IdentityContext>()
            .AddDefaultTokenProviders();

            services.AddMvc(options =>
            {
                //options.Filters.Add(new RequireHttpsAttribute());
                options.SslPort = _sslPort;
            });

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Account/login";
                options.UserInteraction.LogoutUrl = "/Account/logout";
            })
            // Replace with your certificate's thumbPrint, path, and password
            .AddSigningCredential(
                CertificateLoader.Load(
                    "701480955FFC6E5423A267A37F5968E28E4FF31B",
                    Path.Combine(_env.ContentRootPath, "Certificates", "example.pfx"),
                    "OidcTemplate",
                    false))
            .AddInMemoryApiResources(Domain.Authentication.Resources.GetApis(domainSettings.Api))
            .AddInMemoryIdentityResources(Domain.Authentication.Resources.GetIdentityResources())
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;     // interval in seconds
            })
            .AddAspNetIdentity <ApplicationUser>()
            ;


            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddScoped <IProfileService, ProfileService>();
            services.AddScoped <IClientStore, ClientStore>();
            services.AddScoped <ISeedAuthService, SeedAuthService>();
        }
コード例 #8
0
ファイル: Startup.cs プロジェクト: hDar/AuthServer
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var domainSettings = new DomainSettings();

            Configuration.GetSection(nameof(DomainSettings)).Bind(domainSettings);
            services.Configure <DomainSettings>(options => Configuration.GetSection(nameof(DomainSettings)).Bind(options));

            var appSettings = new AppSettings();

            Configuration.GetSection(nameof(AppSettings)).Bind(appSettings);

            var connectionString   = appSettings.ConnectionStrings.AuthContext;
            var migrationsAssembly = typeof(DataModule).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <IdentityContext>(o => o.UseSqlServer(connectionString,
                                                                        optionsBuilder =>
                                                                        optionsBuilder.MigrationsAssembly(typeof(DataModule).GetTypeInfo().Assembly.GetName().Name)));
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <IdentityContext>()
            .AddDefaultTokenProviders();

            services.AddMvc(options =>
            {
                //options.Filters.Add(new RequireHttpsAttribute());
                options.SslPort = _sslPort;
            });

            // Add application services.
            //services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
            services.AddTransient <IEmailSender, EmailSender>();
            //services.AddTransient<IProfileService, ProfileService>();
            services.AddTransient <IClientStore, ClientStore>();
            services.AddTransient <ISeedAuthService, SeedAuthService>();

            services.AddTransient <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>()
            .AddTransient <IProfileService, ProfileService>();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Account/login";
                options.UserInteraction.LogoutUrl = "/Account/logout";
            })
            // Replace with your certificate's thumbPrint, path, and password
            .AddSigningCredential(
                CertificateLoader.Load(
                    "701480955FFC6E5423A267A37F5968E28E4FF31B",
                    Path.Combine(_env.ContentRootPath, "Certificates", "example.pfx"),
                    "OidcTemplate",
                    false))
            //.AddDeveloperSigningCredential()
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;     // interval in seconds
            }).
            AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <ProfileService>();

            /////////////////// Configuration for Auth Server API /////////////////////////////////////

            services.AddMvcCore(options =>
            {
                options.SslPort = _sslPort;
            })
            .AddAuthorization()
            .AddJsonFormatters()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = domainSettings.Auth.Url;
                options.RequireHttpsMetadata = false;
                options.ApiName   = "internal_auth_api";
                options.ApiSecret = domainSettings.Api.Secret;
            });



            services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins(domainSettings.Client.Url)
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });


            services.AddAuthorization(options =>
            {
                options.AddPolicy(DomainPolicies.NormalUser,
                                  policy => policy.RequireClaim(JwtClaimTypes.Scope, DomainScopes.MvcClientUser));
                options.AddPolicy(DomainPolicies.SuperAdmin, policy => policy.RequireClaim(JwtClaimTypes.Role, DomainRoles.SuperAdmin));
                options.AddPolicy(DomainPolicies.Admin, policy => policy.RequireClaim(JwtClaimTypes.Role, DomainRoles.Admin));
            });

            services.AddTransient <IUnitOfWork, SiUnitOfWork>();

            /////////////////// Configuration for Auth Server API ////////////////////////////////////////
        }
コード例 #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            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;
            });

            var domainSettings = new DomainSettings();
            var section        = Configuration.GetSection(nameof(DomainSettings));

            section.Bind(domainSettings);
            services.Configure <DomainSettings>(options => section.Bind(options));

            var appSettings = new AppSettings();

            Configuration.GetSection(nameof(AppSettings)).Bind(appSettings);

            var connectionString   = appSettings.ConnectionStrings.AuthContext;
            var migrationsAssembly = typeof(DataModule).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <IdentityContext>(o => o.UseSqlServer(connectionString,
                                                                        optionsBuilder =>
                                                                        optionsBuilder.MigrationsAssembly(migrationsAssembly)));
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 8;
            })
            .AddEntityFrameworkStores <IdentityContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Account/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
            })
            // Replace with your certificate's thumbPrint, path, and password
            .AddSigningCredential(
                CertificateLoader.Load(
                    "701480955FFC6E5423A267A37F5968E28E4FF31B",
                    Path.Combine(_hostingEnvironment.ContentRootPath, "Certificates", "example.pfx"),
                    "OidcTemplate",
                    false))
            .AddInMemoryApiResources(Domain.Authentication.Resources.GetApis(domainSettings.Api))
            .AddInMemoryIdentityResources(Domain.Authentication.Resources.GetIdentityResources())
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;     // interval in seconds
            })
            .AddAspNetIdentity <ApplicationUser>()
            ;

            services.AddMvc(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddScoped <IProfileService, ProfileService>();
            services.AddScoped <IClientStore, ClientStore>();
            services.AddScoped <ISeedAuthService, SeedAuthService>();
        }
            public void ShouldThrowOnCertificateNotFoundInStore()
            {
                _expectedCertificateStore.Open(OpenFlags.ReadWrite);
                _expectedCertificateStore.Remove(_expectedCertificate);
                _expectedCertificateStore.Close();

                try
                {
                    Assert.ThrowsException <MisconfigurationException>(() => { using (var x = CertificateLoader.Load(AuthenticationMethodProvider.CertificateLocation.Store, _tempStoreInfoPath)) { } });
                }
                finally
                {
                    _expectedCertificateStore.Open(OpenFlags.ReadWrite);
                    _expectedCertificateStore.Add(_expectedCertificate);
                    _expectedCertificateStore.Close();
                }
            }