Exemplo n.º 1
0
        public static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         // uncomment to write to Azure diagnostics stream
                         //.WriteTo.File(
                         //    @"D:\home\LogFiles\Application\identityserver.txt",
                         //    fileSizeLimitBytes: 1_000_000,
                         //    rollOnFileSizeLimit: true,
                         //    shared: true,
                         //    flushToDiskInterval: TimeSpan.FromSeconds(1))
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();



            try
            {
                var host = CreateHostBuilder(args).Build();
                Log.Information("Seed Data...");

                var config = host.Services.GetRequiredService <IConfiguration>();

                var connectionString = config.GetValue <string>("DbConnectionString");
                SeedData.EnsureSeedData(connectionString);
                Log.Information("Starting host...");
                host.Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly.");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Exemplo n.º 2
0
        public static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         // uncomment to write to Azure diagnostics stream
                         //.WriteTo.File(
                         //    @"D:\home\LogFiles\Application\identityserver.txt",
                         //    fileSizeLimitBytes: 1_000_000,
                         //    rollOnFileSizeLimit: true,
                         //    shared: true,
                         //    flushToDiskInterval: TimeSpan.FromSeconds(1))
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code)
                         .CreateLogger();

            var seed = args.Contains("/seed");

            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = CreateHostBuilder(args).Build();

            if (seed)
            {
                Log.Information("Seeding database...");
                var config           = host.Services.GetRequiredService <IConfiguration>();
                var connectionString = config.GetConnectionString("DefaultConnection");
                SeedData.EnsureSeedData(connectionString);
                Log.Information("Done seeding database.");
                return(0);
            }

            Log.Information("Starting host...");
            host.Run();
            return(0);
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            var mutex = new Mutex(true, "IdentityServerDemo", out var isUniqueInstanceOfApplication);

            if (!isUniqueInstanceOfApplication)
            {
                Console.WriteLine("已经有一个服务实例正在运行。");
                Console.WriteLine("按任意键退出……");
                Console.ReadKey();
                Environment.Exit(-2);
            }
#if !DEBUG
            //通过特殊手段运行应用可能导致工作目录与程序文件所在目录不一致,需要调整,否则配置文件和其他数据无法加载(仅限发布模式,调试模式修改工作目录也可能导致配置和其他数据无法加载)
            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
#endif
            var host = CreateWebHostBuilder(args).Build();
            SeedData.EnsureSeedData(host.Services);
            EnsureRequestHandlerIdentificationDoNotHaveDuplicate(host.Services);
            host.Run();
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.File(@"Logs/identityserver4_log.txt")
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            var host = BuildWebHost(args);

            Thread.Sleep(20000);
            SeedData.EnsureSeedData(host.Services);
            host.Run();
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            var seed = args.Any(x => x == "/seed");

            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = CreateWebHostBuilder(args).Build();

            if (seed)
            {
                var config           = host.Services.GetRequiredService <IConfiguration>();
                var connectionString = config.GetConnectionString("Boardy");
                SeedData.EnsureSeedData(connectionString);
                return;
            }

            host.Run();
        }
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    SeedData.EnsureSeedData(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex.ToString());
                }
            }

            host.Run();
        }
        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }

            app.UseStaticFiles();
            //app.UseHttpsRedirection(); //Uncomment to force SSL
            app.UseRouting();
            app.UseIdentityServer();
            app.UseCors("default");
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });

            SeedData.EnsureSeedData(Configuration.GetConnectionString("DefaultConnection"));
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer";

            var seed = args.Contains("/seed");

            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = BuildWebHost(args);

            if (seed)
            {
                SeedData.EnsureSeedData(host.Services);
            }


            BuildWebHost(args).Run();
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServerWithAspNetIdentity";

            var seed = args.Any(x => x == "/seed");

            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = BuildWebHost(args);

            if (seed)
            {
                SeedData.EnsureSeedData(host.Services);
                return;
            }

            host.Run();
        }
Exemplo n.º 10
0
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer4";

            try
            {
                var seed = args.Contains("/seed");
                if (seed)
                {
                    args = args.Except(new[] { "/seed" }).ToArray();
                }

                //seed = true;
                var host = CreateWebHostBuilder(args).Build();

                if (seed)
                {
                    Log.Information("Seeding database...");
                    var config           = host.Services.GetRequiredService <IConfiguration>();
                    var connectionString = config.GetConnectionString("DefaultConnection");
                    SeedData.EnsureSeedData(connectionString);
                    Log.Information("Done seeding database.");
                }

                Log.Information("Starting host...");
                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly.");
            }
            finally
            {
                Log.CloseAndFlush();
            }

            //CreateWebHostBuilder(args).Build().Run();
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer4.EntityFramework";

            var seed = args.Contains("/seed");

            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = CreateWebHostBuilder(args).Build();

            if (seed)
            {
                var config           = host.Services.GetRequiredService <IConfiguration>();
                var connectionString = config.GetConnectionString("DefaultConnection");
                SeedData.EnsureSeedData(connectionString);
                return;
            }

            host.Run();
        }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public async void ConfigureServices(IServiceCollection services)
        {
            // Ensure that our in-memory database does not lose state between connections.
            AnchorInMemoryDatabase();

            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 <ApplicationDbContext>(
                options => options.UseSqlite(_sqlite)
                );

            services.AddIdentity <ApplicationUser, IdentityRole>(config => { config.SignIn.RequireConfirmedEmail = false; })
            // .AddDefaultUI(UIFramework.Bootstrap4) // Disabled because it causes UI to be included as Razor class lib.
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath        = $"/Identity/Account/Login";
                options.LogoutPath       = $"/Identity/Account/Logout";
                options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
            });

            // using Microsoft.AspNetCore.Identity.UI.Services;
            services.AddSingleton <IEmailSender, EmailSender>();

            // Run all the migrations and seed tables with default values.
            await SeedData.EnsureSeedData(services, _sqlite);

            services.AddMvcCore()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddAuthorization(options =>
            {
                options.AddPolicy
                (
                    ManagementApiPolicies.Admin,
                    policy => policy.RequireClaim(ApplicationClaimTypes.ROLE, AccountsApiRoles.ADMIN)
                );
            })
            .AddJsonFormatters();

            // This will add Cookie Authentication, but will still need JWT/Bearer Authentication
            var identityBuilder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                                  .AddInMemoryIdentityResources(Config.GetIdentityResources())
                                  .AddInMemoryApiResources(Config.GetApis())
                                  .AddInMemoryClients(Config.GetClients(Configuration))
                                  .AddAspNetIdentity <ApplicationUser>();

            // Now, add JWT/Bearer Authentication.  Without this, calls from APIs
            // won't be authenticated.
            // https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = Configuration["IdentityServer:Authority:Url"];
                options.ApiName              = ApplicationScopes.USER_MANAGEMENT_API;
                options.RequireHttpsMetadata = false;

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = OnAccessTokenAuthenticationFailed,
                    OnTokenValidated       = OnAccessTokenValidated,
                    OnMessageReceived      = OnAccessTokenMessageReceived
                };
            });

            if (Environment.IsDevelopment())
            {
                identityBuilder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }
        }
Exemplo n.º 13
0
 private void InitializeDatabase(IApplicationBuilder app)
 {
     SeedData.EnsureSeedDataUsers(app.ApplicationServices);
     SeedData.EnsureSeedData(Configuration.GetConnectionString("DefaultConnection"));
 }