Пример #1
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"
                };
            });
        }
 // 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;
 }
Пример #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)
 {
     //ADD IDENTITY SERVER
     services.AddIdentityServer()
     .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources())
     .AddTestUsers(InMemoryConfig.GetUsers())
     .AddInMemoryClients(InMemoryConfig.GetClients())
     .AddDeveloperSigningCredential();
 }
Пример #4
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>();
        }
Пример #5
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();
        }
Пример #6
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
                }));
            });
        }
Пример #7
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();
        }
Пример #8
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();
        }
Пример #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)
        {
            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();
        }
Пример #10
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;
                    }
                }
            }
        }
Пример #11
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
            });
        }