public static void AddIdentityServerCustom(this IServiceCollection services,
                                                   IConfiguration configuration)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]   = configuration["ClientUrl:Mvc"],
                ["Admin"] = configuration["ClientUrl:Admin"],
            };

            var connectionString = configuration.GetConnectionString("ApplicationConnection");

            var assembly = typeof(Startup).Assembly.GetName().Name;

            services.AddIdentity <IdentityUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                // config.Cookie.Name = "server";
                config.LoginPath  = "/Auth/Login";
                config.LogoutPath = "/Auth/Logout";
            });

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddAspNetIdentity <IdentityUser>()
            // .AddConfigurationStore(options =>
            // {
            //     options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
            //         sql => sql.MigrationsAssembly(assembly));
            // })
            // .AddOperationalStore(options =>
            // {
            //     options.ConfigureDbContext = b =>
            //         b.UseSqlServer(connectionString, sql =>
            //             sql.MigrationsAssembly(assembly));
            // })
            .AddProfileService <ProfileService>()
            .AddInMemoryIdentityResources(IdentityServerConfig.Ids)
            .AddInMemoryApiResources(IdentityServerConfig.Apis)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddDeveloperSigningCredential();
            // .AddTestUsers(TestUsers.Users)
        }
Example #2
0
        private void InitializeDatabase(IApplicationBuilder app)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]   = Configuration["ClientUrl:Mvc"],
                ["Admin"] = Configuration["ClientUrl:Admin"],
            };

            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

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

                context.Database.Migrate();

                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityServerConfig.Clients(clientUrls))
                    {
                        context.Clients.Add(client.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    foreach (var resource in IdentityServerConfig.Ids)
                    {
                        context.IdentityResources.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.ApiResources.Any())
                {
                    foreach (var resource in IdentityServerConfig.Apis)
                    {
                        context.ApiResources.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }

                if (!context.ApiScopes.Any())
                {
                    foreach (var resource in IdentityServerConfig.ApiScopes)
                    {
                        context.ApiScopes.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }
            }
        }
Example #3
0
        public async Task <IActionResult> OnPost(string returnUrl = null)
        {
            var requestHeader = HttpContext.Request.Headers["Referer"].ToString();
            await _signInManager.SignOutAsync();

            _logger.LogInformation("User logged out.");

            var logoutId = this.Request.Query["logoutId"].ToString();

            if (returnUrl != null)
            {
                return(LocalRedirect(returnUrl));
            }
            else if (!string.IsNullOrEmpty(logoutId))
            {
                var logoutContext = await this._interaction.GetLogoutContextAsync(logoutId);

                returnUrl = logoutContext.PostLogoutRedirectUri;

                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return(this.Redirect(returnUrl));
                }
                else
                {
                    var clientIdtemp = logoutContext.ClientIds.ToArray()[0];
                    var referer      = IdentityServerConfig.Clients(Startup.clientUrls).Where(item => item.ClientId == clientIdtemp).First();
                    if (referer != null)
                    {
                        return(this.Redirect(referer.FrontChannelLogoutUri));
                    }
                    return(Page());
                }
            }
            else
            {
                return(RedirectToPage());
            }
        }
        public static void AddIdentityServerCustom(this IServiceCollection services, IConfiguration configuration)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = configuration["ClientUrl:Mvc"],
                ["Swagger"] = configuration["ClientUrl:Swagger"],
                ["React"]   = configuration["ClientUrl:React"]
            };

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.EmitStaticAudienceClaim       = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <User>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential();
        }
Example #5
0
        public static void InitializeDatabase(this IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>().Database.Migrate();
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();
                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                context.Database.Migrate();
                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityServerConfig.Clients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }
                    context.SaveChanges();
                }

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

                if (!context.ApiResources.Any())
                {
                    foreach (var resource in IdentityServerConfig.ApiResources())
                    {
                        context.ApiResources.Add(resource.ToEntity());
                    }
                    context.SaveChanges();
                }
            }
        }
Example #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            clientUrls = new Dictionary <string, string>
            {
                ["CustomerSite"] = Configuration["clientUrl:CustomerSite"],
                ["BackEnd"]      = Configuration["clientUrl:Backend"],
                ["ReactAdmin"]   = Configuration["clientUrl:ReactAdmin"]
            };

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

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity <User>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.EmitStaticAudienceClaim       = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <User>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential();

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

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

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlSerializerFormatters();

            services.AddCors();

            services.AddControllersWithViews();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Rookie API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            TokenUrl         = new Uri("/connect/token", UriKind.Relative),
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes           = new Dictionary <string, string> {
                                { "rookieshop.api", "Rookie API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "rookieshop.api"
                        }
                    }
                });
            });
        }
        /*     public static Dictionary<string, string> clientUrls;*/

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = Configuration["ClientUrl:Mvc"],
                ["Swagger"] = Configuration["ClientUrl:Swagger"],
                ["React"]   = Configuration["ClientUrl:React"]
            };
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();


            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.EmitStaticAudienceClaim       = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <IdentityUser>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential();    // not recommended for production - you need to store your key material

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

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

            services.AddTransient <IStorageService, FileStorageService>();
            services.AddTransient <IRateRepository, RateRepository>();
            services.AddControllersWithViews()
            .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
            services.AddControllersWithViews()

            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Rookie Shop API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            TokenUrl         = new Uri("/connect/token", UriKind.Relative),
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes           = new Dictionary <string, string> {
                                { "rookieshop.api", "Rookie Shop API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "rookieshop.api"
                        }
                    }
                });
            });
        }
Example #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = Configuration["ClientUrl:Mvc"],
                ["Blazor"]  = Configuration["ClientUrl:Blazor"],
                ["Swagger"] = Configuration["ClientUrl:Swagger"],
                ["Angular"] = Configuration["ClientUrl:Angular"]
            };

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

            services.AddTransient <IStorageService, FileStorageService>();

            services.AddDefaultIdentity <User>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.Ids)
            .AddInMemoryApiResources(IdentityServerConfig.Apis)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <User>()
            .AddDeveloperSigningCredential();     // not recommended for production - you need to store your key material somewhere secure

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

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

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins(clientUrls["Blazor"], clientUrls["Angular"])
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MyShop API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{clientUrls["Swagger"]}/connect/authorize"),
                            Scopes           = new Dictionary <string, string> {
                                { "api.myshop", "My Shop API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "api.myshop"
                        }
                    }
                });
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = Configuration["ClientUrl:Mvc"],
                ["Swagger"] = Configuration["ClientUrl:Swagger"],
                ["React"]   = Configuration["ClientUrl:React"]
            };

            services.AddDbContext <MyDBContext>(options =>
                                                options.UseSqlServer(
                                                    Configuration.GetConnectionString("RookieConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity <IdentityUser>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredUniqueChars    = 0;
            })
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <MyDBContext>();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.EmitStaticAudienceClaim       = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryClients(IdentityServerConfig.Clients((clientUrls)))
            .AddAspNetIdentity <IdentityUser>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential(); // not recommended for production - you need to store your key material somewhere secure

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

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

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

                options.AddPolicy("AdminOrUser", policy =>
                {
                    policy.AddAuthenticationSchemes("Bearer");
                    policy.RequireAuthenticatedUser();
                    policy.RequireRole("Admin", "User");
                });
            });


            services.AddScoped <ICategorySevice, CategoryService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IRatingService, RatingService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IFilesService, FilesService>();

            services.AddControllersWithViews().AddNewtonsoftJson(options =>
                                                                 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                                 );
            ;

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Simple Shop API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            TokenUrl         = new Uri("/connect/token", UriKind.Relative),
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes           = new Dictionary <string, string> {
                                { "product.api", "Simple Shop API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "product.api"
                        }
                    }
                });
            });
        }
Example #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = Configuration["ClientUrl:Mvc"],
                ["Swagger"] = Configuration["ClientUrl:Swagger"],
                ["React"]   = Configuration["ClientUrl:React"]
            };

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddTransient <IStorageService, FileStorageService>();
            services.AddDefaultIdentity <User>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

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

            services.AddControllersWithViews();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.EmitStaticAudienceClaim       = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <User>()
            .AddProfileService <CustomProfileService>()
            .AddDeveloperSigningCredential();    // not recommended for production - you need to store your key material somewhere secure

            services.AddAuthentication()
            .AddLocalApi("Bearer", option =>
            {
                option.ExpectedScope = "ewbokrookies.api";
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Bearer", policy =>
                {
                    policy.AddAuthenticationSchemes("Bearer");
                    policy.RequireAuthenticatedUser();
                });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "EWBOK_Rookies", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            TokenUrl         = new Uri("/connect/token", UriKind.Relative),
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes           = new Dictionary <string, string> {
                                { "ewbokrookies.api", "EWBOK_Rookies API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "ewbokrookies.api"
                        }
                    }
                });
            });
        }
Example #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Mvc"]     = Configuration["ClientUrl:Mvc"],
                ["Blazor"]  = Configuration["ClientUrl:Blazor"],
                ["Swagger"] = Configuration["ClientUrl:Swagger"],
                ["Angular"] = Configuration["ClientUrl:Angular"],
                ["React"]   = Configuration["ClientUrl:React"]
            };

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

            services.AddTransient <IStorageService, FileStorageService>();

            services.AddDefaultIdentity <User>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddInMemoryIdentityResources(IdentityServerConfig.Ids)
            .AddInMemoryApiResources(IdentityServerConfig.Apis)
            .AddInMemoryClients(IdentityServerConfig.Clients(clientUrls))
            .AddAspNetIdentity <User>()
            .AddDeveloperSigningCredential();     // not recommended for production - you need to store your key material somewhere secure

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

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

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins(clientUrls["Blazor"], clientUrls["Angular"])
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MyShop API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            TokenUrl         = new Uri("/connect/token", UriKind.Relative),
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes           = new Dictionary <string, string> {
                                { "api.myshop", "My Shop API" }
                            }
                        },
                    },
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new List <string> {
                            "api.myshop"
                        }
                    }
                });
            });

            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddOpenTelemetryTracing(tracing =>
            {
                tracing.AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddSource("OTel.Demo")
                .SetSampler(new AlwaysOnSampler())
                .AddZipkinExporter(option =>
                {
                    option.ServiceName = typeof(Startup).Assembly.GetName().Name;
                    option.Endpoint    = new Uri("http://localhost:9411/api/v2/spans");
                });
            });
        }
Example #12
0
        public static void InitializeDatabase(this IApplicationBuilder app, IConfiguration configuration)
        {
            var clientUrls = new Dictionary <string, string>
            {
                ["Web"]       = configuration["ClientUrl:Web"],
                ["Admin-web"] = configuration["ClientUrl:Admin_web"],
                ["Swagger"]   = configuration["ClientUrl:Swagger"],
                ["Idp"]       = configuration["ClientUrl:Idp"],
                ["Service"]   = configuration["ClientUrl:Service"]
            };

            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var persistantContext = serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>();
                var context           = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

                //CleanClients(context);
                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityServerConfig.Clients(clientUrls))
                    {
                        context.Clients.Add(client.ToEntity());
                    }
                    context.SaveChanges();
                }

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

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

                if (!context.ApiScopes.Any())
                {
                    context.ApiScopes.Add(new ApiScope
                    {
                        Name        = "api.minecommerce",
                        DisplayName = "api.minecommerce",
                        Enabled     = true
                    });
                    context.SaveChanges();
                }

                var applicationDbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                //CleanUser(applicationDbContext);
                if (!applicationDbContext.Users.Any())
                {
                    var adminRole = new IdentityRole("Admin")
                    {
                        Id             = Guid.NewGuid().ToString(),
                        NormalizedName = "admin".ToUpper(),
                    };
                    var userRole = new IdentityRole("User")
                    {
                        Id             = Guid.NewGuid().ToString(),
                        NormalizedName = "user".ToUpper()
                    };
                    var roles = new List <IdentityRole>
                    {
                        adminRole, userRole
                    };

                    applicationDbContext.Roles.AddRange(roles);
                    applicationDbContext.SaveChanges();

                    var passwordHasher = new PasswordHasher <IdentityUser>();
                    var user           = new IdentityUser("*****@*****.**");
                    user.Id                 = Guid.NewGuid().ToString();
                    user.Email              = "*****@*****.**";
                    user.NormalizedEmail    = "*****@*****.**".ToUpper();
                    user.NormalizedUserName = "******".ToUpper();
                    user.EmailConfirmed     = true;
                    user.PasswordHash       = passwordHasher.HashPassword(user, "Ch@ngeMe");
                    user.AccessFailedCount  = 0;

                    applicationDbContext.Users.Add(user);
                    applicationDbContext.SaveChanges();

                    applicationDbContext.UserRoles.Add(new IdentityUserRole <string>
                    {
                        UserId = user.Id,
                        RoleId = adminRole.Id
                    });
                    applicationDbContext.SaveChanges();
                }
            }
        }