public void Initialize()
        {
            if (!_configDbContext.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClients().ToList())
                {
                    _configDbContext.Clients.Add(client.ToEntity());
                }
                _configDbContext.SaveChanges();
            }


            if (!_configDbContext.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetIdentityResources().ToList())
                {
                    _configDbContext.IdentityResources.Add(resource.ToEntity());
                }
                _configDbContext.SaveChanges();
            }

            if (!_configDbContext.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources().ToList())
                {
                    _configDbContext.ApiResources.Add(resource.ToEntity());
                }
                _configDbContext.SaveChanges();
            }
        }
        private static void EnsureSeedData(ConfigurationDbContext context)
        {
            if (!context.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClientScope().ToList())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }


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

            if (!context.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources().ToList())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
예제 #3
0
 public static void Performseed(ConfigurationDbContext context)
 {
     if (!context.Clients.Any())
     {
         foreach (var client in IdentityServerConfiguration.GetClients())
         {
             context.Clients.Add(client.ToEntity());
         }
         context.SaveChanges();
     }
     if (!context.IdentityResources.Any())
     {
         foreach (var resource in IdentityServerConfiguration.GetIdentityResources())
         {
             context.IdentityResources.Add(resource.ToEntity());
         }
         context.SaveChanges();
     }
     if (!context.ApiResources.Any())
     {
         foreach (var api in IdentityServerConfiguration.GetApiResources())
         {
             context.ApiResources.Add(api.ToEntity());
         }
         context.SaveChanges();
     }
 }
예제 #4
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryClients(IdentityServerConfiguration.GetClientScope())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddTestUsers(IdentityServerConfiguration.GetUsers().ToList());
 }
예제 #5
0
 private void ConfigureIdentityServer(IServiceCollection services, string connectionString, IConfiguration configuration)
 {
     services.AddIdentityServer(c =>
     {
         c.Endpoints = GetEndpointsOptions();
         c.Discovery = GetDiscoveryOptions();
     })
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryClients(IdentityServerConfiguration.GetClients(BuildClientUriConfigurationDictionary(Configuration)))
     .AddAspNetIdentity <User>()
     .AddDeveloperSigningCredential();
 }
예제 #6
0
        public async Task Initialize()
        {
            this._context.Database.Migrate();
            this._persistedGrantContext.Database.Migrate();
            this._configContext.Database.Migrate();

            if (!this._context.Roles.Any(r => r.Name.Equals(Roles.ADMIN)) || !this._userManager.Users.Any(u => u.UserName.Equals(Roles.ADMIN)))
            {
                await this._roleManager.CreateAsync(new IdentityRole(Roles.ADMIN));

                await this._roleManager.CreateAsync(new IdentityRole(Roles.USER));

                await this._userManager.CreateAsync(new UserEntity { UserName = Roles.ADMIN, Email = ADMIN_EMAIL }, ADMIN_PASS);

                await this._userManager.AddToRoleAsync(await this._userManager.FindByNameAsync(Roles.ADMIN), Roles.ADMIN);
            }

            if (!_configContext.Clients.Any())
            {
                foreach (var client in IdentityServerConfiguration.GetClients())
                {
                    this._configContext.Clients.Add(client.ToEntity());
                }
            }

            if (!_configContext.IdentityResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetIdentityResources())
                {
                    this._configContext.IdentityResources.Add(resource.ToEntity());
                }
            }

            if (!_configContext.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources())
                {
                    this._configContext.ApiResources.Add(resource.ToEntity());
                }
            }

            await this._context.SaveChangesAsync();

            await this._configContext.SaveChangesAsync();

            await this._persistedGrantContext.SaveChangesAsync();
        }
 public static IServiceCollection ConfigureIdentityServer(this IServiceCollection services)
 {
     services.AddIdentityServer().AddDeveloperSigningCredential()
     // this adds the operational data from DB (codes, tokens, consents)
     .AddOperationalStore(options =>
     {
         options.ConfigureDbContext = builder => builder.UseSqlServer(ConfigurationResolver.GetConfiguration().GetConnectionString("SQLServer"));
         // this enables automatic token cleanup. this is optional.
         options.EnableTokenCleanup   = true;
         options.TokenCleanupInterval = 30;     // interval in seconds
     })
     .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
     .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
     .AddInMemoryClients(IdentityServerConfiguration.GetClients())
     .AddAspNetIdentity <User>();
     return(services);
 }
예제 #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            services.AddCors();

            services.AddAuthentication();
            services.AddAuthorization();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Logout";
            })
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients())
            .AddInMemoryApiScopes(IdentityServerConfiguration.GetApiScopes())
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
            .AddDeveloperSigningCredential();

            services.AddControllersWithViews();
        }
예제 #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            NLog.LogManager.Configuration = new NLogLoggingConfiguration(Configuration.GetSection("NLog"));

            services.AddHealthChecks();
            services.AddHttpClient();
            services.AddDbContext <DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TaskAPI")));

            var identityServerOptions = new Common.Options.IdentityServerOptions();

            Configuration.Bind("IdentityServer", identityServerOptions);

            var certificatePath = Path.Combine(Directory.GetCurrentDirectory(), identityServerOptions.CertFolder, identityServerOptions.CertFile);

            Console.WriteLine(certificatePath);

            services.AddIdentityServer()
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources(identityServerOptions.Scope))
            .AddInMemoryClients(IdentityServerConfiguration.GetClients(identityServerOptions.ClientId, identityServerOptions.ClientSecret))
            .AddResourceOwnerValidator <CustomResourceOwnerPasswordValidator>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential()
            /** .AddSigningCredential(new X509Certificate2(certificatePath, identityServerOptions.CertPassword)) **/
            ;

            services.AddMvcCore().AddApiExplorer();

            services
            .AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
            });
        }
예제 #10
0
        public static void Main(string[] args)
        {
            Console.Title = "Chat Api";

            var host = WebHost
                       .CreateDefaultBuilder(args)
                       .ConfigureAppConfiguration((context, config) =>
            {
                var environment = context.HostingEnvironment;

                config
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                if (environment.IsDevelopment())
                {
                    config.AddUserSecrets <Program>();
                }

                if (null != args)
                {
                    config.AddCommandLine(args);
                }
            })
                       .ConfigureServices((context, services) =>
            {
                var environment = context.HostingEnvironment;

                if (environment.IsDevelopment())
                {
                }

                services
                .TryAddSingleton(provider =>
                {
                    var client = new ClientBuilder()
                                 .UseLocalhostClustering()
                                 .Configure <ClusterOptions>(options =>
                    {
                        options.ClusterId = "dev";
                        options.ServiceId = "chatroom-local";
                    })
                                 .ConfigureLogging(logging =>
                    {
                        logging.AddConsole();
                    })
                                 .AddSimpleMessageStreamProvider(Constants.StreamProviders.ChatRooms)
                                 .Build();

                    var awaiter = client.Connect().GetAwaiter();

                    awaiter.GetResult();

                    return(client);
                });

                services
                .AddDbContext <ChatIdentityDbContext>(options =>
                {
                    options.UseSqlite(context.Configuration.GetConnectionString("Chat"));
                })
                .AddIdentity <Customer, CustomerRole>(options =>
                {
                    options.User.RequireUniqueEmail = true;
                })
                .AddEntityFrameworkStores <ChatIdentityDbContext>()
                .AddDefaultTokenProviders();

                services
                .AddIdentityServer(options =>
                {
                    options.Endpoints = new EndpointsOptions
                    {
                        EnableDiscoveryEndpoint    = true,
                        EnableAuthorizeEndpoint    = true,
                        EnableCheckSessionEndpoint = true,
                        EnableEndSessionEndpoint   = true,
                        EnableUserInfoEndpoint     = true
                    };

                    //options.Events.RaiseErrorEvents = true;
                    //options.Events.RaiseSuccessEvents = true;

                    options.UserInteraction.LoginUrl   = "/account/signin";
                    options.UserInteraction.ConsentUrl = "/consent/confirm";
                    options.UserInteraction.ErrorUrl   = "/account/error";
                })
                // https://github.com/IdentityServer/IdentityServer4/blob/44651bea9b02c992902639b21205f433aad47d03/src/IdentityServer4/src/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs
                .AddSigninCredentials(context.Configuration.GetSection("IdentityServer:Key"))
                .AddAspNetIdentity <Customer>()
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = database =>
                    {
                        database.UseSqlite(context.Configuration.GetConnectionString("Identity"));
                    };
                })
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = database =>
                    {
                        database.UseSqlite(context.Configuration.GetConnectionString("Identity"));
                    };
                });

                services
                .AddAutoMapper(options =>
                {
                    // action results
                    options
                    .CreateMap <RoomDescription, RoomCreatedResult>()
                    .ForMember(
                        result => result.Id,
                        map => map.MapFrom(source => source.Id)
                        )
                    .ForMember(
                        result => result.Name,
                        map => map.MapFrom(source => source.Name)
                        )
                    .ForMember(
                        result => result.Description,
                        map => map.MapFrom(source => source.Description)
                        );

                    options
                    .CreateMap <RoomDescription, RoomResult>()
                    .ForMember(
                        result => result.Id,
                        map => map.MapFrom(source => source.Id)
                        )
                    .ForMember(
                        result => result.Name,
                        map => map.MapFrom(source => source.Name)
                        )
                    .ForMember(
                        result => result.Description,
                        map => map.MapFrom(source => source.Description)
                        );

                    options
                    .CreateMap <RoomDescription, RoomDetails>()
                    .ForMember(
                        result => result.Id,
                        map => map.MapFrom(source => source.Id)
                        )
                    .ForMember(
                        result => result.Name,
                        map => map.MapFrom(source => source.Name)
                        )
                    .ForMember(
                        result => result.Description,
                        map => map.MapFrom(source => source.Description)
                        );
                },
                               typeof(Program).Assembly
                               );

                services
                .AddMediatR(
                    typeof(Program).Assembly
                    );

                services
                .AddLogging()
                .AddSingleton <IChatRoomRegistry, ChatRoomRegistry>()
                .AddWebSocketHandlers(options =>
                {
                    options.Register <ChatRoomWebSocketHandler>("api/chat/{room:long}");
                })
                .AddControllers(options =>
                {
                    options.EnableEndpointRouting = true;
                });

                services
                .AddRazorPages(options =>
                {
                    //options.RootDirectory = "/Pages";
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

                services
                .AddHsts(options =>
                {
                    options.Preload           = true;
                    options.IncludeSubDomains = true;
                    //options.ExcludedHosts.Add("http://localhost:5000");
                })
                .AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 5001;
                });

                services
                .AddOidcStateDataFormatterCache()
                .AddAuthorization(options =>
                                  options.AddPolicy(
                                      "Customers",
                                      policy => policy.RequireClaim("role", "Customer")
                                      )
                                  )
                //.AddAuthentication(IdentityConstants.ApplicationScheme)
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.Authority            = "https://localhost:5001";
                    options.RequireHttpsMetadata = true;

                    options.Audience = "chat.api";

                    options.TokenValidationParameters.RoleClaimType = "role";
                })
                //.AddOpenIdConnect()
                ;

                services.ConfigureApplicationCookie(options =>
                {
                    options.Cookie.Name = "Chat.Identity";
                });

                services
                .AddTransient <ISigninService <Customer, long>, EntityFrameworkSigninService>();

                var seed = context.Configuration.GetValue <string>("seed");

                if (false == String.IsNullOrEmpty(seed))
                {
                    services.AddScoped <ConfigurationDbSetup>();
                }
            })
                       .Configure(app =>
            {
                var provider    = app.ApplicationServices;
                var environment = provider.GetRequiredService <IWebHostEnvironment>();

                if (environment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                    app.UseHsts();
                }

                app
                .UseHttpsRedirection()
                .UseStaticFiles()
                .UseWebSockets(new WebSocketOptions
                {
                    KeepAliveInterval = TimeSpan.FromSeconds(30.0d),
                    ReceiveBufferSize = 8096
                })
                .UseMiddleware <WebSocketsMiddleware>()
                .UseAuthentication()
                .UseIdentityServer()
                .UseRouting()
                .UseAuthorization()
                .UseEndpoints(routes =>
                {
                    routes.MapControllers();
                });
            })
                       .Build();

            host.MigrateDbContext <ConfigurationDbContext>(async(context, services) =>
            {
                var setup = services.GetService <ConfigurationDbSetup>();

                if (null != setup)
                {
                    await setup.SeedAsync(
                        IdentityServerConfiguration.GetClients(),
                        IdentityServerConfiguration.GetIdentityResources(),
                        IdentityServerConfiguration.GetApiResources()
                        );
                }
            });

            host.Run();
        }
예제 #11
0
        /// <summary>
        /// Configura os serviços do sistema
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();
            services.AddAutofac();

            services.AddApiVersioning(p =>
            {
                p.DefaultApiVersion = new ApiVersion(1, 0);
                p.ReportApiVersions = true;
                p.AssumeDefaultVersionWhenUnspecified = true;
            });

            ContainerBuilder container = new ContainerBuilder();

            services.AddMvc(options =>
            {
                options.Filters.Add(new HeaderFilter());
                options.Filters.Add(new ProtocolFilter());
                //options.Filters.Add(new ValidatorFilter());
            });

            services.ConfigureOptions(Configuration);

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()     //AddSigningCredential()
            .AddInMemoryClients(IdentityServerConfiguration.GetClients())
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiScopes(IdentityServerConfiguration.GetApiScopes())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
            .AddResourceOwnerValidator <Application.Auth.ResourceOwnerPasswordValidator>();
            //.AddLdapUsers<OpenLdapAppUser>(Configuration.GetSection("ldapActiveDirectory"), UserStore.InMemory);

            // Configurando o serviço de documentação do Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title       = "Sistema de recursos humanos",
                    Version     = "v1",
                    Description = "API REST para manutenção de dados de colaboradores da Susep",
                });

                string caminhoAplicacao =
                    PlatformServices.Default.Application.ApplicationBasePath;
                string nomeAplicacao =
                    PlatformServices.Default.Application.ApplicationName;
                string caminhoXmlDoc =
                    Path.Combine(caminhoAplicacao, $"{nomeAplicacao}.xml");

                c.IncludeXmlComments(caminhoXmlDoc);
            });


            services.ConfigureOptions(Configuration);

            container.Populate(services);
            container.RegisterModule(new MediatorModuleConfiguration());
            container.RegisterModule(new ApplicationModuleConfiguration(Configuration));

            return(new AutofacServiceProvider(container.Build()));
        }
예제 #12
0
        public static void Init(IServiceProvider scopeServiceProvider)
        {
            var userManager = scopeServiceProvider.GetService <UserManager <IdentityUser> >();

            var user = new IdentityUser
            {
                UserName = "******"
            };
            var author = new IdentityUser
            {
                UserName = "******"
            };
            var editor = new IdentityUser
            {
                UserName = "******"
            };

            var resultUser   = userManager.CreateAsync(user, "123qwe").GetAwaiter().GetResult();
            var resultAuthor = userManager.CreateAsync(author, "123qwe").GetAwaiter().GetResult();
            var resultEditor = userManager.CreateAsync(editor, "123qwe").GetAwaiter().GetResult();

            if (resultUser.Succeeded && resultAuthor.Succeeded && resultEditor.Succeeded)
            {
                userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "User")).GetAwaiter().GetResult();
                userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Scope, "OrdersAPI")).GetAwaiter().GetResult();
                userManager.AddClaimAsync(author, new Claim(ClaimTypes.Role, "Author")).GetAwaiter().GetResult();
                userManager.AddClaimAsync(author, new Claim(JwtClaimTypes.Scope, "OrdersAPI")).GetAwaiter().GetResult();
                userManager.AddClaimAsync(editor, new Claim(ClaimTypes.Role, "Editor")).GetAwaiter().GetResult();
                userManager.AddClaimAsync(editor, new Claim(JwtClaimTypes.Scope, "OrdersAPI")).GetAwaiter().GetResult();
            }

            scopeServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

            var context = scopeServiceProvider.GetRequiredService <ConfigurationDbContext>();

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

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

            if (!context.ApiResources.Any())
            {
                foreach (var resource in IdentityServerConfiguration.GetApiResources())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }