示例#1
0
        public void ConfigureServices(IServiceCollection services)
        {
            var    migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            string connectionString   = "";

            if (_currentEnvironment.IsDevelopment())
            {
                connectionString = _configuration.GetConnectionString("DefaultConnection");
            }
            else
            {
                connectionString = ConnectionUri.Convert(Environment.GetEnvironmentVariable("DATABASE_URL"));
            }

            services.AddDbContext <ApplicationDbContext>(config =>
            {
                //config.UseSqlServer(connectionString);
                config.UseNpgsql(connectionString);
            });
            // register repositories(collection of fuctions, interfaces that abstracts your calls to the database)
            services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                config.Cookie.Name = "IdentityServer.Cookie";
                config.LoginPath   = "/Account/Login";
            });

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;

                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
            })
            .AddAspNetIdentity <ApplicationUser>()

            /*.AddConfigurationStore(options =>//configuration in Configuration.cs file client, api, identity etc
             * {
             *  options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
             *      sql => sql.MigrationsAssembly(migrationsAssembly));
             * })
             * .AddOperationalStore(options =>//this is mainly about operational like keep track of authorization code
             * {
             *  options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
             *      sql => sql.MigrationsAssembly(migrationsAssembly));
             * .AddTestUsers(TestUsers.Users)
             * })*/
            .AddInMemoryIdentityResources(Configuration.GetIdentityResources())
            .AddInMemoryApiScopes(Configuration.ApiScopes)
            .AddInMemoryClients(Configuration.GetClients())
            .AddDeveloperSigningCredential();


            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                // register your IdentityServer with Google at https://console.developers.google.com
                // enable the Google+ API
                // set the redirect URI to https://localhost:5001/signin-google
                options.ClientId     = "copy client ID from Google here";
                options.ClientSecret = "copy client secret from Google here";
            });


            services.AddControllersWithViews();
        }
示例#2
0
文件: Program.cs 项目: bds0900/pizza
        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();

            try
            {
                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    env              = host.Services.GetRequiredService <IWebHostEnvironment>();
                    string connectionString = "";
                    if (env.IsDevelopment())
                    {
                        connectionString = config.GetConnectionString("DefaultConnection");
                    }
                    else
                    {
                        connectionString = ConnectionUri.Convert(Environment.GetEnvironmentVariable("DATABASE_URL"));
                    }
                    SeedData.EnsureSeedData(connectionString);
                    Log.Information("Done seeding database.");
                    return(0);
                }

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