private void SetupDatabase()
        {
            _connectionString = Configuration["DbContextSettings:ConnectionString"];

            // Use Heroku's injected connection string instead of appsettings' if present
            if (HerokuConfiguration.IsAvailable())
            {
                _connectionString = HerokuConfiguration.GetConnectionString();
            }

            // If this configuration key has been injected, it means Startup is being called by the dotnet cli command
            // and we do not want to migrate the database during that process.
            //if (Configuration["EFToolBeingUsed"] != "true")
            //{
            //    MigrateDabatase();
            //}
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = CurrentEnvironment.IsDevelopment()
                ? Configuration.GetConnectionString("DefaultConnection")
                : HerokuConfiguration.GetHerokuConnectionString();

            services.AddControllers()
            .AddJsonOptions(options =>
                            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

            var jwtOptions    = new JwtOptions();
            var configSection = Configuration.GetSection("JwtOptions");

            configSection.Bind(jwtOptions);

            services.Configure <JwtOptions>(configSection);

            // Custom BadRequest response on ModelState validation
            services.Configure <ApiBehaviorOptions>(o =>
            {
                o.CustomInvalidModelStateResponse();
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidIssuer      = jwtOptions.Issuer,
                    ValidateAudience = false,
                    //ValidAudience = authOptions.Audience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = jwtOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         { options.UseNpgsql(connectionString); });

            services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddRoles <IdentityRole>()
            .AddRoleManager <RoleManager <IdentityRole> >()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddScoped <IJwtGenerator, JwtGenerator>();

            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddCors();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Identity CQRS API",
                    Description = "A simple Asp.Net Core web API which uses CQRS MediatR pattern to handle requests " +
                                  "and Identity to communicate with database. Used jwt authentication."
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }