示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
                    ClockSkew        = TimeSpan.Zero
                };
                services.AddCors();
            });

            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                config.AddPolicy(Policies.User, Policies.UserPolicy());
                config.AddPolicy(Policies.Customer, Policies.CustomerPolicy());
            });

            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc().AddNewtonsoftJson();

            services.AddIdentity <IdentityUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit     = true;
                options.Password.RequireLowercase = true;
                options.Password.RequiredLength   = 5;
            }).AddEntityFrameworkStores <MarketplaceDB>();

            services.AddScoped <IJWTService, JWTService>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
                    ClockSkew        = TimeSpan.Zero
                };
            });

            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                config.AddPolicy(Policies.Customer, Policies.CustomerPolicy());
                config.AddPolicy(Policies.Seller, Policies.SellerPolicy());
            });


            services.AddDbContext <MarketplaceDB>(
                options => options.UseSqlServer(Configuration.GetConnectionString("MarketPlaceDatabase"))
                );



            services.AddTransient <IMailService, MailService>();

            services.AddScoped <ISellerService, SellerService>();

            services.AddScoped <ICustomerService, CustomerService>();

            services.AddScoped <IAdminService, AdminService>();

            services.AddScoped <IImageService, ImageService>();
            services.AddScoped <IEncryptService, EncryptService>();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <mysiteContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("mysitedb")));

            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );;
            services.AddHttpContextAccessor();
            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
                    ClockSkew        = TimeSpan.Zero
                };
            });
            services.AddCors();
            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                config.AddPolicy(Policies.Customer, Policies.CustomerPolicy());
            });



            services.AddDistributedSqlServerCache(options =>
            {
                options.ConnectionString = Configuration.GetConnectionString("mysitedb");//"Server =BEAST; Database = mysite; Trusted_Connection = true";
                options.SchemaName       = "dbo";
                options.TableName        = "SessionData";
            });
            services.AddSession(options =>
            {
                options.Cookie.Name        = "KhalisStore.Session";
                options.IdleTimeout        = System.TimeSpan.FromHours(48);
                options.Cookie.HttpOnly    = false;
                options.Cookie.IsEssential = true;
            });
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Inject AppSettings
            services.Configure <ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));

            services.AddControllers();

            services.AddDbContext <StoreContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

            services.AddCors();

            // Add Repository
            services.AddScoped <AddressRepository>();
            services.AddScoped <ApplicationUserRepository>();
            services.AddScoped <OrderProductRepository>();
            services.AddScoped <OrderRepository>();
            services.AddScoped <ProductRepository>();

            //Jwt Authentication
            var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:JWT_Secret"].ToString());

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = false;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ClockSkew = TimeSpan.Zero
                };
            });

            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                config.AddPolicy(Policies.Employee, Policies.EmployeePolicy());
                config.AddPolicy(Policies.Customer, Policies.CustomerPolicy());
            });

            // This service fixes an error i get when i try to include in entity framework. MESSAGE ERROR: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth) at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );
        }
示例#5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.OutputFormatters.RemoveType <StringOutputFormatter>();
                options.OutputFormatters.RemoveType <HttpNoContentOutputFormatter>();
            }).AddXmlSerializerFormatters()

            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters        = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors         = true;
                options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404";
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Jwt:Audience"],
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                options.AddPolicy(Policies.Customer, Policies.CustomerPolicy());
            });
            services.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
            var logFactory = LoggerFactory.Create(b => b.AddConsole().AddDebug());

            services.AddDbContext <AppDbContext>(options =>
            {
                options
                .UseSqlServer(Configuration.GetConnectionString("AppConnection"))
                .EnableSensitiveDataLogging()
                .UseLoggerFactory(logFactory);
            });

            services.AddTransient <IProductService, ProductService>();
        }
示例#6
0
 public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
         options.TokenValidationParameters = new TokenValidationParameters //TokenValidationParameters tell wt do want to validate here
         {
             ValidateIssuerSigningKey = true,                              // if we forget this user send up any old token they want bcz we would never validate that the signing key is correct
             IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:key"])),
             ValidIssuer      = config["Token:Issuer"],
             ValidateIssuer   = true,
             ValidateAudience = false
         };
     });
     services.AddAuthorization(config =>
     {
         config.AddPolicy(roles.Pharmacy.ToString(), Policies.PharmacyPolicy());
         config.AddPolicy(roles.Customer.ToString(), Policies.CustomerPolicy());
         config.AddPolicy(roles.DeliveryBoy.ToString(), Policies.DeliveryBoyPolicy());
     });
     return(services);
 }
示例#7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool <AppDbContext>(options =>
            {
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title   = "RenCart API",
                    Contact = new OpenApiContact
                    {
                        Name  = "Pritish ranjan barik",
                        Email = "*****@*****.**",
                        Url   = new Uri("http://localhost:80")
                    },
                    Description = "RenCart E-Commerce API for Book Store",
                    Version     = "v1"
                });
                var xmlFile  = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var fullPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(fullPath);

                x.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "Standard JWT Authorization header. Example: \"bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
            });

            services.AddScoped <ITokenService, TokenService>();

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddAutoMapper(x => x.AddProfile(typeof(MappingProfile)));
            services.AddDataAccessLayers();

            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(opts =>
            {
                opts.RequireHttpsMetadata = false;
                opts.SaveToken            = true;

                opts.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ValidIssuer      = Configuration["AppSettings:Issuer"],
                    ValidAudience    = Configuration["AppSettings:Audience"],
                    ClockSkew        = TimeSpan.Zero,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppSettings:SecretKey"])),
                    RoleClaimType    = ClaimTypes.Role
                };
            });
            services.AddAuthorization(opts =>
            {
                opts.AddPolicy(Policy.Admin, Policies.AdminPolicy());
                opts.AddPolicy(Policy.Customer, Policies.CustomerPolicy());
                opts.AddPolicy(Policy.Manager, Policies.ManagerPolicy());
                opts.DefaultPolicy = Policies.CustomerPolicy();
            });

            services.AddCors();
            services.AddControllers();
        }