// 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" }; }); }
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); }
// 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; }
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) { //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>(); }
// 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(); }
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(); }
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(); } }
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();//ÅäÖÃÈÏÖ¤·þÎñ }
// 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 })); }); }
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>(); } }
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(); } }
// 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(); }
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); }
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; } } } }
// 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 }); }