Exemplo n.º 1
0
    /// <summary>
    /// Swaps the config state with a new snapshot of the configuration, then signals that the old one is outdated.
    /// </summary>
    public void Update(IReadOnlyList <RouteConfig> routes, IReadOnlyList <ClusterConfig> clusters)
    {
        var newConfig = new InMemoryConfig(routes, clusters);
        var oldConfig = Interlocked.Exchange(ref _config, newConfig);

        oldConfig.SignalChange();
    }
Exemplo n.º 2
0
        /// <summary>
        /// Swaps the config state with a new snapshot of the configuration, then signals the change
        /// </summary>
        public void Update(IReadOnlyList <ProxyRoute> routes, IReadOnlyList <Cluster> clusters)
        {
            var oldConfig = _config;

            _config = new InMemoryConfig(routes, clusters);
            oldConfig.SignalChange();
        }
Exemplo n.º 3
0
        // 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)
        {
            services.AddControllersWithViews();

            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
                          .AddInMemoryApiScopes(InMemoryConfig.GetApiScopes())
                          .AddInMemoryClients(InMemoryConfig.GetClients())
                          .AddTestUsers(InMemoryConfig.GetUsers());

            builder.AddDeveloperSigningCredential();

            services.AddAuthentication()
            .AddOpenIdConnect("oidc", "Demo IdentityServer", options =>
            {
                options.SignInScheme  = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;
                options.SaveTokens    = true;

                options.Authority    = "https://demo.identityserver.io/";
                options.ClientId     = "interactive.confidential";
                options.ClientSecret = "cepres";
                options.ResponseType = "code";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });
        }
 private void AndroidAppSetup_Load(object sender, EventArgs e)
 {
     InMemoryConfig config = InMemoryConfig.Instance;
     config.LoadRegKey();
     labelPort.Text = config._port.ToString();
     labelIp.Text = GetIp();
 }
Exemplo n.º 5
0
        public static IHost MigrateDatabase(this IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                using (var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>())
                {
                    try
                    {
                        context.Database.Migrate();

                        if (!context.Clients.Any())
                        {
                            foreach (var client in InMemoryConfig.GetClients())
                            {
                                context.Clients.Add(client.ToEntity());
                            }
                            context.SaveChanges();
                        }

                        if (!context.IdentityResources.Any())
                        {
                            foreach (var resource in InMemoryConfig.GetIdentityResources())
                            {
                                context.IdentityResources.Add(resource.ToEntity());
                            }
                            context.SaveChanges();
                        }

                        if (!context.ApiScopes.Any())
                        {
                            foreach (var apiScope in InMemoryConfig.GetApiScopes())
                            {
                                context.ApiScopes.Add(apiScope.ToEntity());
                            }

                            context.SaveChanges();
                        }

                        if (!context.ApiResources.Any())
                        {
                            foreach (var resource in InMemoryConfig.GetApiResources())
                            {
                                context.ApiResources.Add(resource.ToEntity());
                            }
                            context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Log errors or do anything you think it's needed
                        throw;
                    }
                }
            }

            return(host);
        }
Exemplo n.º 6
0
 // 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)
 {
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryApiResources(InMemoryConfig.ApiResources())
     .AddInMemoryClients(InMemoryConfig.ApiClients())
     .AddTestUsers(InMemoryConfig.Users().ToList());
 }
 public static IIdentityServerBuilder AddInMemoryConfiguration(this IIdentityServerBuilder builder, IConfigurationSection config)
 {
     return builder
         .AddInMemoryIdentityResources(InMemoryConfig.GetIds(config.GetSection("Ids")))
         .AddInMemoryApiResources(InMemoryConfig.GetApis(config.GetSection("Apis")))
         .AddInMemoryApiScopes(InMemoryConfig.GetApiScopes(config.GetSection("Apis")))
         .AddInMemoryClients(InMemoryConfig.GetClients(config.GetSection("Clients")));
 }
 // 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)
 {
     services.AddIdentityServer()
     .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
     .AddTestUsers(InMemoryConfig.GetUsers())
     .AddInMemoryClients(InMemoryConfig.GetClients())
     .AddDeveloperSigningCredential(); //not something we want to use in a production environment;
 }
Exemplo n.º 9
0
 // 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)
 {
     //ADD IDENTITY SERVER
     services.AddIdentityServer()
     .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
     .AddTestUsers(InMemoryConfig.GetUsers())
     .AddInMemoryClients(InMemoryConfig.GetClients())
     .AddDeveloperSigningCredential();
 }
Exemplo n.º 10
0
        // 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 migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
                                                                           b =>
            {
                b.MigrationsAssembly("Launchpad.App");
            })
                                                         );

            services.AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            //.AddDefaultTokenProviders();

            //var x = services.AddIdentityServer(option =>
            //{
            //    option.IssuerUri = Configuration.GetSection("Identity").GetValue<string>("Authority");
            //})
            //    .AddTestUsers(InMemoryConfig.GetUsers())
            //    .AddInMemoryClients(InMemoryConfig.GetClients())
            //    .AddConfigurationStore(opt =>
            //    {
            //        opt.ConfigureDbContext = c =>
            //        c.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
            //        sql => sql.MigrationsAssembly("Launchpad.App"));
            //    })
            //.AddOperationalStore(opt =>
            // {
            //     opt.ConfigureDbContext = c =>
            //     c.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
            //     sql => sql.MigrationsAssembly("Launchpad.App"));
            // })
            //    .AddDeveloperSigningCredential()
            //    .AddAspNetIdentity<User>();

            services.AddIdentityServer(option =>
            {
                option.IssuerUri = Configuration.GetSection("Identity").GetValue <string>("Authority");
            })
            .AddOperationalStore(opt =>
            {
                opt.ConfigureDbContext = c =>
                                         c.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
                                                     sql => sql.MigrationsAssembly("Launchpad.App"));
            })


            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddInMemoryApiResources(InMemoryConfig.ApiResources)
            .AddInMemoryApiScopes(InMemoryConfig.ApiScopes)
            .AddInMemoryClients(InMemoryConfig.GetClients())
            .AddAspNetIdentity <User>();
        }
Exemplo n.º 11
0
        private void SaveInformation()
        {
            // store config values in settings
            InMemoryConfig config = InMemoryConfig.Instance;

            config._port       = int.Parse(textBoxPort.Text);
            config._syncFolder = textBoxSyncFolder.Text;
            config._password   = HashUtil.MD5Hash(textBoxPassword.Text);
            config.SaveRegKey();
        }
Exemplo n.º 12
0
        public void Update(IReadOnlyList <ProxyRoute> routes, IReadOnlyList <Cluster> clusters)
        {
            Console.WriteLine("Removed oldConfig");
            var oldConfig = _config;

            _config = new InMemoryConfig(routes, clusters);
            oldConfig.SignalChange();

            Console.WriteLine($"count = {count++}");
        }
Exemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddInMemoryClients(InMemoryConfig.GetClients())
            .AddDeveloperSigningCredential();     // Not for production. Use AddSigningCredentials

            services.AddControllersWithViews();
        }
Exemplo n.º 14
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();


            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            // IdentityResources 用户相关权限
            .AddInMemoryIdentityResources(InMemoryConfig.IdentityResources())
            // api访问权限
            .AddInMemoryApiScopes(InMemoryConfig.ApiScopes)
            // 客户端配置
            .AddInMemoryClients(InMemoryConfig.Clients())
            // 测试用户
            .AddTestUsers(TestUsers.Users)

            //扩展在每次启动时,为令牌签名创建了一个临时密钥
            .AddDeveloperSigningCredential();

            services.AddAuthentication()
            //覆盖 Cookie 处理程序配置
            .AddCookie("Cookies")
            //.AddGoogle("Google", options =>
            //  {
            //      options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
            //      options.ClientId = "clientID";
            //      options.ClientSecret = "clientSecret";
            //  })
            //远程测试
            .AddOpenIdConnect("oidc", "Demo IdentityServer", options =>
            {
                options.SignInScheme  = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;
                options.SaveTokens    = true;

                options.Authority    = "https://demo.identityserver.io/";
                options.ClientId     = "interactive.confidential";
                options.ClientSecret = "secret";
                options.ResponseType = "code";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });
        }
Exemplo n.º 15
0
        private static void InitializeConfigurationDbContext(IConfiguration seedDataConfig, IServiceScope serviceScope)
        {
            serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

            var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            context.Database.Migrate();

            if (seedDataConfig == null)
            {
                return;
            }

            if (!context.Clients.Any())
            {
                foreach (var client in InMemoryConfig.GetClients(seedDataConfig.GetSection("Clients")))
                {
                    context.Clients.Add(client.ToEntity());
                }

                context.SaveChanges();
            }

            if (!context.IdentityResources.Any())
            {
                foreach (var resource in InMemoryConfig.GetIds(seedDataConfig.GetSection("Ids")))
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }

                context.SaveChanges();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var resource in InMemoryConfig.GetApis(seedDataConfig.GetSection("Apis")))
                {
                    context.ApiResources.Add(resource.ToEntity());
                }

                foreach (var resource in InMemoryConfig.GetApiScopes(seedDataConfig.GetSection("Apis")))
                {
                    context.ApiScopes.Add(resource.ToEntity());
                }

                context.SaveChanges();
            }
        }
Exemplo n.º 16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            }).AddTestUsers(InMemoryConfig.Users().ToList())
                          .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
                          .AddInMemoryClients(InMemoryConfig.GetClients());

            builder.AddDeveloperSigningCredential();
            services.AddAuthentication();//ÅäÖÃÈÏÖ¤·þÎñ
        }
Exemplo n.º 17
0
 private static void AddIdentityServer(IServiceCollection services, IWebHostEnvironment environment)
 {
     if (environment.IsEnvironment("Test"))
     {
         services.AddIdentityServer()
         .AddApiAuthorization <ApplicationUser, ApplicationDbContext>()
         //api resources
         .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
         .AddInMemoryApiScopes(InMemoryConfig.GetApiScopes())
         .AddTestUsers(InMemoryConfig.Users().ToList())
         .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
         .AddInMemoryClients(InMemoryConfig.GetClients());
     }
     else
     {
         services.AddIdentityServer()
         .AddApiAuthorization <ApplicationUser, ApplicationDbContext>();
     }
 }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddControllers();

            services.AddOpenApiDocument(config =>
            {
                // Document name (default to: v1)
                config.DocumentName = "AdminWebCore";

                // Document / API version (default to: 1.0.0)
                config.Version = "1.0.0";

                // Document title (default to: My Title)
                config.Title = "AdminWebCore";

                // Document description
                config.Description = "AdminWebCore documentation";
            });

            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options => {
                options.Authority            = "https://localhost:44301";
                options.RequireHttpsMetadata = false;
            });

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()         //not something we want to use in a production environment
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddInMemoryClients(InMemoryConfig.GetClients());

            services.AddSwaggerDocument(config => {
                config.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT Token",
                                                                             new OpenApiSecurityScheme
                {
                    Type        = OpenApiSecuritySchemeType.ApiKey,
                    Name        = "Authorization",
                    Description = "Copy 'Bearer ' + valid JWT token into field",
                    In          = OpenApiSecurityApiKeyLocation.Header
                }));
            });
        }
Exemplo n.º 19
0
        private static void EnsureSeedData(ConfigurationDbContext context)
        {
            if (!context.Clients.Any())
            {
                Console.WriteLine("Clients 正在初始化");
                foreach (var client in InMemoryConfig.GetClients())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.IdentityResources.Any())
            {
                Console.WriteLine("IdentityResources 正在初始化");
                foreach (var resource in InMemoryConfig.GetIdentityResources())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.ApiResources.Any())
            {
                Console.WriteLine("ApiResources 正在初始化");
                foreach (var resource in InMemoryConfig.GetApiResources())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.ApiScopes.Any())
            {
                Console.WriteLine("ApiScopes 正在初始化");
                foreach (var resource in InMemoryConfig.GetApiScopes())
                {
                    context.ApiScopes.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddDeveloperSigningCredential()     //not something we want to use in a production environment;
            .AddConfigurationStore(opt =>
            {
                opt.ConfigureDbContext = c => c.UseSqlServer(Configuration.GetConnectionString("sqlConnection"),
                                                             sql => sql.MigrationsAssembly(migrationAssembly));
            })
            .AddOperationalStore(opt =>
            {
                opt.ConfigureDbContext = o => o.UseSqlServer(Configuration.GetConnectionString("sqlConnection"),
                                                             sql => sql.MigrationsAssembly(migrationAssembly));
            });

            services.AddControllersWithViews();
        }
Exemplo n.º 21
0
        // 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)
        {
            //ADD IDENTITY SERVER
            services.AddIdentityServer()
            .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddInMemoryClients(InMemoryConfig.GetClients())
            .AddDeveloperSigningCredential();


            //add authentication
            services.AddAuthentication("Bearer").AddJwtBearer("Bearer", opt =>
            {
                opt.RequireHttpsMetadata = false;
                opt.Authority            = "https://localhost:5005";
                opt.Audience             = "companyApi";
            });

            //add view and controller
            services.AddControllersWithViews();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureLoggerService();
            services.AddDbContext <HealthCare020DbContext>(x =>
                                                           x.UseSqlServer(Configuration.GetConnectionString("Healthcare020")).EnableSensitiveDataLogging(true));

            services.AddIdentityServer(opt =>
            {
                opt.IssuerUri = Resources.ProductionUri;
                opt.Discovery.CustomEntries.Add("face-recognition", $"~/{Routes.FaceRecognitionRoute}");
            })
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddInMemoryClients(InMemoryConfig.GetClients())
            .AddInMemoryApiResources(InMemoryConfig.Apis)
            .AddDeveloperSigningCredential()
            .AddCorsPolicyService <InMemoryCorsPolicyService>()
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
            .AddProfileService <ProfileService>();

            services.AddHealthCare020Services(Configuration);

            services.AddControllers();
        }
Exemplo n.º 23
0
        // 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 migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
            //.AddInMemoryApiScopes(InMemoryConfig.GetApiScopes())
            //.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
            //.AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            //.AddInMemoryClients(InMemoryConfig.GetClients())
            .AddDeveloperSigningCredential()
            .AddConfigurationStore(opt =>
            {
                opt.ConfigureDbContext = c => c.UseSqlServer(Configuration.GetConnectionString("sqlConnection"),
                                                             sql => sql.MigrationsAssembly(migrationAssembly));
            })
            .AddOperationalStore(opt =>
            {
                opt.ConfigureDbContext = o => o.UseSqlServer(Configuration.GetConnectionString("sqlConnection"),
                                                             sql => sql.MigrationsAssembly(migrationAssembly));
            });

            services.AddControllersWithViews();
        }
Exemplo n.º 24
0
 public InMemoryConfigProvider(IReadOnlyList <ProxyRoute> routes, IReadOnlyList <Cluster> clusters)
 {
     _config = new InMemoryConfig(routes, clusters);
 }
Exemplo n.º 25
0
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Swagger"] = configuration["ClientUrl:Swagger"],
                ["Mvc"]     = configuration["ClientUrl:Mvc"],
                ["React"]   = configuration["ClientUrl:React"]
            };

            if (configuration.GetValue <bool>("UseInMemoryDatabase"))
            {
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             options.UseInMemoryDatabase("MsCoreOneDb"));
            }
            else
            {
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             options.UseSqlServer(
                                                                 configuration.GetConnectionString("DefaultConnection"),
                                                                 b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));
            }

            services.AddScoped <IApplicationDbContext>(provider => provider.GetService <ApplicationDbContext>());

            services.AddDefaultIdentity <ApplicationUser>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
            .AddInMemoryClients(InMemoryConfig.GetClients(clientUrls))
            .AddAspNetIdentity <ApplicationUser>()
            .AddDeveloperSigningCredential();

            services.AddTransient <IIdentityService, IdentityService>();
            services.AddTransient <IStorageService, FileStorageService>();

            services.AddAuthentication()
            .AddLocalApi("Bearer", option =>
            {
                option.ExpectedScope = "api.mscoreone";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Bearer", policy =>
                {
                    policy.AddAuthenticationSchemes("Bearer");
                    policy.RequireAuthenticatedUser();
                });
            });

            services.AddCors(options =>
            {
                options.AddPolicy("MsCoreOneOrigins",
                                  builder =>
                {
                    builder.WithOrigins(clientUrls["Mvc"], clientUrls["React"], clientUrls["Swagger"])
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.ConfigureApplicationCookie(c =>
            {
                c.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = (ctx) =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        return(Task.CompletedTask);
                    },
                    OnRedirectToAccessDenied = (ctx) =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 403;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddSingleton <IUriService>(o =>
            {
                return(new UriService(clientUrls["Swagger"]));
            });

            return(services);
        }
Exemplo n.º 26
0
        private void FillIs4DataBase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                if (serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.EnsureCreated())
                {
                    try
                    {
                        var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                        context.Database.Migrate();
                        if (!context.Clients.Any())
                        {
                            foreach (var client in InMemoryConfig.GetClients())
                            {
                                context.Clients.Add(client.ToEntity());
                            }
                            context.SaveChanges();
                        }
                        if (!context.IdentityResources.Any())
                        {
                            foreach (var resource in InMemoryConfig.GetIdentityResources())
                            {
                                context.IdentityResources.Add(resource.ToEntity());
                            }
                            context.SaveChanges();
                        }
                        if (!context.ApiScopes.Any())
                        {
                            foreach (var apiScope in InMemoryConfig.GetApiScopes())
                            {
                                context.ApiScopes.Add(apiScope.ToEntity());
                            }
                            context.SaveChanges();
                        }
                        if (!context.ApiResources.Any())
                        {
                            foreach (var resource in InMemoryConfig.GetApiResources())
                            {
                                context.ApiResources.Add(resource.ToEntity());
                            }
                            context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }

                    try
                    {
                        var manager     = serviceScope.ServiceProvider.GetRequiredService <SignInManager <IdentityUser> >();
                        var usercontext = serviceScope.ServiceProvider.GetRequiredService <IdentityUsersContext>();
                        usercontext.Database.Migrate();
                        if (!usercontext.Users.Any())
                        {
                            foreach (var user in InMemoryConfig.GetUsers())
                            {
                                var newUser = new IdentityUser
                                {
                                    UserName = user.Username,
                                    Id       = user.SubjectId
                                };
                                newUser.PasswordHash = new PasswordHasher <IdentityUser>().HashPassword(newUser, user.Password);
                                var task = Task.Run(async() => { await manager.UserManager.CreateAsync(newUser); });
                                task.Wait();
                                foreach (var claim in user.Claims)
                                {
                                    usercontext.UserClaims.Add(
                                        new IdentityUserClaim <string>
                                    {
                                        ClaimType  = claim.Type,
                                        ClaimValue = claim.Value,
                                        UserId     = user.SubjectId
                                    });
                                    usercontext.SaveChanges();
                                }
                            }
                        }
                        if (!usercontext.UserRoles.Any())
                        {
                            usercontext.Roles.Add(new IdentityRole("manager"));
                            usercontext.Roles.Add(new IdentityRole("developer"));
                            usercontext.SaveChanges();
                        }
                        //if (!usercontext.UserClaims.Any())
                        //{
                        //    foreach (var user in InMemoryConfig.GetUsers())
                        //    {

                        //    }
                        //    usercontext.SaveChanges();
                        //}
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //important for json serialization Support -- input and output json formatter
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection2")));

            //register the interfaces
            services.AddScoped <IStudent, StudentRepo>();


            //Add IdentityServer
            services.AddIdentityServer()
            .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
            .AddTestUsers(InMemoryConfig.GetUsers())
            .AddInMemoryClients(InMemoryConfig.GetClients())
            .AddDeveloperSigningCredential(); //not something we want to use in a production environment;

            // /*
            //the small piece below configures cookies in identity to return the right thing "401" on redirect to login
            services.ConfigureApplicationCookie(options =>
            {
                //on trying to redirect to login page for authentication return 401
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = 401;
                    return(Task.CompletedTask);
                };
                //on trying to redirect to acces denied gives us 403
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = 403;
                    return(Task.CompletedTask);
                };
            });

            //*/

            //Swagger configuration
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v2", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title       = "Student API Service",
                    Version     = "v2",
                    Description = "A simple student Api...",
                });

                // -- provided security is implemented

                //For Authorization Key Button to come up, and to activate token from SwaggerUI
                options.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
                {
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Type         = SecuritySchemeType.Http,
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer"
                });

                //Helps to tell swagger which of our actions require Authorization.
                options.OperationFilter <AuthenticationRequirementsOperationFilter>();

                services.AddMvcCore().AddApiExplorer();  // Service Needed for swagger to work with .netcoremvc
            });
        }