示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IUserRepository, UserRepository> ();
            services.AddScoped <IVegetableRepository, VegetableRepository> ();
            services.AddScoped <IMeatRepository, MeatRepository> ();
            services.AddScoped <IEntreeRepository, EntreeRepository> ();


            services.AddScoped <IUnitOfWork, UnitOfWork> ();

            services.AddAutoMapper();

            services.AddDbContext <FaDbContext> (options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

            services.AddMvc();

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();                     // For anyone access.
            corsBuilder.WithOrigins("http://localhost:4200"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options => {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
示例#2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <PetsDbContext>(options =>
                                                  options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <User, IdentityRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <PetsDbContext>()
            .AddDefaultTokenProviders();

            services.AddDomainServices();

            services.AddAutoMapper();

            services.AddRouting(routing => routing.LowercaseUrls = true);

            //services.AddCors();

            ////services.AddMvc();
            ////services.Configure<MvcOptions>(options =>
            ////{
            ////  options.Filters.Add(new CorsAuthorizationFilterFactory("http://localhost:4200"));
            ////});

            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                                  builder => builder.WithOrigins("http://localhost:4200"));
            });

            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling =
                                                 Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:4200"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });
        }
示例#3
0
        public static IServiceCollection AddCorsConfiguration(this IServiceCollection services)
        {
            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", corsBuilder.Build());
            });

            return(services);
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <WebApi.EmailSettings.EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddScoped <IEmailSender, AuthMessageSender>();
            ConfigureRepositoryService(services);

            services.AddAutoMapper();

            services.AddDbContext <FcDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

            services.AddMvc();

            // ********************
            // Setup CORS
            // ********************
            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();                                                                    // For anyone access.
            corsBuilder.WithOrigins("http://localhost:4200", "https://familycoredevsite.azurewebsites.net"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });


            ConfigureJwtAuthService(services);

            // add identity
            var builder = services.AddIdentityCore <AppUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <FcDbContext>().AddDefaultTokenProviders();

            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());
        }
示例#5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
示例#6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region MVC
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
            #endregion

            #region Inject EF DbContext
            services.AddDbContext <FamilyHubDbContext>(options => options.UseSqlServer(Configuration["AppSettings:ConnectionString"]));
            #endregion

            #region Register AutoMapper Service
            services.AddAutoMapper(typeof(FamilyHubAutoMapperConfiguration));
            #endregion

            #region Inject Business Service Layer
            services.AddScoped <ICommonService, CommonService>();
            services.AddScoped <IMemberService, MemberService>();
            services.AddScoped <ITransactionsService, TransactionsService>();
            services.AddScoped <IPaymentService, PaymentService>();
            services.AddScoped <IIOptionService, IOptionService>();
            #endregion

            #region Inject Auth Service Layer
            services.AddScoped <ITokenService, TokenService>();
            services.AddTransient <IPasswordHasher, PasswordHasher>();
            #endregion

            #region Inject IUserInfo by registering it as a service
            services.AddScoped <IUserInfo>(provider =>
            {
                var context = provider.GetService <IHttpContextAccessor>();

                if (context.HttpContext != null)
                {
                    return(new UserInfo
                    {
                        UID = Convert.ToInt32(context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)),
                        Email = context.HttpContext.User.FindFirstValue(ClaimTypes.Name)
                    });
                }
                else
                {
                    return(null);
                }
            });
            #endregion

            #region Configure JwtIssuerOptions
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
            var _signingKey          = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JwtIssuerOptions:ServerSigningPassword"]));
            #endregion

            #region Configure Jwt Options
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
                options.ValidFor           = TimeSpan.FromMinutes(Convert.ToInt32(jwtAppSettingOptions[nameof(JwtIssuerOptions.ValidFor)]));
            });
            #endregion

            #region Configure Jwt Authentication
            services.AddAuthentication(options =>
            {
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                #region Jwt Validation Rule
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                    ValidateAudience = true,
                    ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["JwtIssuerOptions:ServerSigningPassword"])),

                    // Validate the token expiry
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero //the default for this setting is 5 minutes
                };
                #endregion

                options.Events = new JwtBearerEvents
                {
                    #region Jwt After Validation Authenticated
                    //OnTokenValidated = async context =>
                    //{
                    //    #region Get user's immutable object id from claims that came from ClaimsPrincipal
                    //    //var userEmail = context.Principal.Claims.Where(c => c.Type == ClaimTypes.Name)
                    //    //       .Select(c => c.Value).SingleOrDefault();
                    //    //var role = context.Principal.Claims.Where(c => c.Type == ClaimTypes.Role)
                    //    //       .Select(c => c.Value).SingleOrDefault();
                    //    #endregion

                    //    #region Use Service
                    //    //var _commonService = context.HttpContext.RequestServices.GetRequiredService<ICommonService>();
                    //    //var internalUserResponse = await _commonService.GetUserAsync(userEmail);
                    //    #endregion
                    //},
                    #endregion

                    #region Jwt After Validation Failed
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add(AuthService.Helper.Constants.JwtTokenResult.TokenExpired, "true");
                        }
                        else if (context.Exception.GetType() == typeof(SecurityTokenInvalidSignatureException) ||
                                 context.Exception.GetType() == typeof(SecurityTokenInvalidSigningKeyException) ||
                                 context.Exception.GetType() == typeof(SecurityTokenInvalidIssuerException) ||
                                 context.Exception.GetType() == typeof(SecurityTokenInvalidAudienceException)
                                 )
                        {
                            context.Response.Headers.Add(AuthService.Helper.Constants.JwtTokenResult.TokenInvalid, "true");
                        }
                        return(Task.CompletedTask);
                    }
                    #endregion
                };
            });
            #endregion

            #region Configure Jwt Authorization
            services.AddAuthorization(options =>
            {
                #region Policy-based Authorization
                options.AddPolicy(AuthService.Helper.Constants.JwtPolicys.RoleAdminRequired,
                                  policy => policy.RequireRole("ADMIN"));
                #endregion

                #region Claim-based Authorization
                // use a claims-based authorization check to give the role access to certain controllers and actions
                // so that only users possessing the role claim may access those resources.
                // build and register a policy called ApiUser which checks for the presence of the Rol claim with a value of ApiAccess.
                //    options.AddPolicy("ApiUser", policy => policy.RequireClaim(
                //        AuthService.Helper.Constants.Strings.JwtClaimIdentifiers.Rol,
                //        AuthService.Helper.Constants.Strings.JwtClaims.ApiAccess));
                //    options.AddPolicy("InternalOnly", policy => policy.RequireClaim(
                //        AuthService.Helper.Constants.Strings.JwtClaimIdentifiers.InternalUser,
                //        AuthService.Helper.Constants.Strings.JwtClaims.ApiInternalAccess));
                #endregion
            });
            #endregion


            #region Setup CORS
            var corsBuilder = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();                     // For anyone access.
            corsBuilder.WithOrigins("http://localhost:4200"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
            #endregion
        }