Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton <IAuthenticator, Authenticator>();
            services.AddSingleton <UserRepository>();
            services.AddSingleton <TokenRepository>();
            services.AddSingleton <Configuration>();
            services.AddSingleton <MailSender>();
//            services.AddHostedService<CronWorker>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = AuthOptions.AUDIENCE,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <ILoggerManager, LoggerManager>();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Api", Version = "v1"
                });
                OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
                {
                    Name         = "Bearer",
                    BearerFormat = "JWT",
                    Scheme       = "bearer",
                    Description  = "Specify the authorization token.",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.Http,
                };
                c.AddSecurityDefinition("jwt_auth", securityDefinition);

                // Make sure swagger UI requires a Bearer token specified
                OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme()
                {
                    Reference = new OpenApiReference()
                    {
                        Id   = "jwt_auth",
                        Type = ReferenceType.SecurityScheme
                    }
                };
                OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
                {
                    { securityScheme, new string[] { } },
                };
                c.AddSecurityRequirement(securityRequirements);
                c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
            });

            services.AddHttpContextAccessor();


            services.AddIdentityCore <ApplicationUser>().
            AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <IdentityContext>();

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

            BL.Configuration.Injection.InfrastructureConfiguration.Configure(services);
            BL.Configuration.Injection.InfrastructureConfiguration.
            DbContext(services, Configuration.GetConnectionString("FilesDb"), Configuration.GetConnectionString("IdentityConnection"));

            services.AddTransient <IAccountService, AccountService>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IAdminService, AdminService>();
            services.AddTransient <IRoleService, RoleService>();
            services.AddTransient <ILinkService, LinkService>();



            services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })

            .AddJwtBearer(options => {
                options.RequireHttpsMetadata = false;

                options.SaveToken = false;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = "API",
                    ValidateAudience         = true,
                    ValidAudience            = "Postman",
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });


            //   services.AddSingleton<UserManager<ApplicationUser>>();
            // services.AddTransient<IAccountService, AccountService>();



            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 8;
            });
            services.AddCors();
        }
Exemplo n.º 3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(i => i.AddProfile(new ApiMapperProfile()), typeof(Startup));
            services.AddControllers(op => op.Filters.Add(typeof(ExceptionFilter)))
            .AddFluentValidation(config =>
            {
                config.LocalizationEnabled = true;
                config.RegisterValidatorsFromAssembly(GetType().Assembly);
            });

            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Events.OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden,
                                                                            options.Events.OnRedirectToAccessDenied);
                options.Events.OnRedirectToLogin =
                    ReplaceRedirector(HttpStatusCode.Unauthorized, options.Events.OnRedirectToLogin);
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthOptions.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = AuthOptions.Audience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };

                options.Cookie.Name      = "access_token";
                options.Cookie.HttpOnly  = true;
                options.TicketDataFormat =
                    new JwtDataFormat(SecurityAlgorithms.HmacSha256, tokenValidationParameters);
            });

            services.AddTransient <IDataBaseService, DataBaseService>();

            services.AddDbContext <PhoneBookContext>(options =>
                                                     options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "PhoneBook API",
                    Description = "ASP.NET Core Web API"
                });
            });

            //services.AddSession(options =>
            //{
            //    options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
            //});

            services.AddCors(options =>
            {
                options.AddPolicy(AllowOrigin, builder => builder.WithOrigins("http://localhost:8080")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials());
            });


            services.AddMvc();
        }
Exemplo n.º 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddSwaggerGenNewtonsoftSupport();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "EventManager API",
                    Description    = "API documentation of 'EventManager API'",
                    TermsOfService = new Uri("https://steventmanagerdev01.z13.web.core.windows.net/"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Kirill Kuznetsov" + " " + @"GitHub Repository",
                        Email = string.Empty,
                        Url   = new Uri("https://github.com/KuznetsovKirill/EventManager")
                    }
                });

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

            services.AddScoped(_ => {
                IConfigurationSection azureConnectionString =
                    Configuration.GetSection("Azure");
                return(new BlobServiceClient(azureConnectionString["AzureStorage"]));
            });

            var authOptions = Configuration.GetSection("AuthOptions").Get <AuthOptions>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                //options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = authOptions.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = authOptions.Audience,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(authOptions.SecretKey),
                    ValidateIssuerSigningKey = true,
                };
            })
            .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                    Configuration.GetSection("Authentication:Google");

                options.ClientId     = googleAuthNSection["ClientId"];
                options.ClientSecret = googleAuthNSection["ClientSecret"];
                options.Scope.Add("email");
            })
            .AddCookie()
            .AddFacebook(facebookOptions =>
            {
                IConfigurationSection facebookAuthNSection =
                    Configuration.GetSection("Authentication:FaceBook");
                facebookOptions.AppId        = facebookAuthNSection["AppId"];
                facebookOptions.AppSecret    = facebookAuthNSection["AppSecret"];
                facebookOptions.CallbackPath = "/api/user/facebook-response";
            });

            // Add scheduled tasks & scheduler
            services.AddSingleton <IScheduledTask, CheckFinishedEventTask>();
            services.AddSingleton <IScheduledTask, SubscriptionEmailTask>();

            services.AddScheduler((sender, args) =>
            {
                Console.Write(args.Exception.Message);
                args.SetObserved();
            });

            ContainerConfiguration.Configure(services, _settings);
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddFluentValidation(validator =>
            {
                validator.RegisterValidatorsFromAssemblyContaining <RegisterUserValidator>();
                validator.RegisterValidatorsFromAssemblyContaining <AuthenticateUserValidator>();
                validator.RegisterValidatorsFromAssemblyContaining <BookValidator>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDbContext <ApplicationContext>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionStrings:BookApp"]);
            }, ServiceLifetime.Scoped);
            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <ApplicationContext>()
            .AddDefaultTokenProviders();

            services.AddScoped(x => x.GetRequiredService <ApplicationContext>().Books);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = AuthOptions.ISSUER,

                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = AuthOptions.AUDIENCE,

                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // установка ключа безопасности
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });


            services.AddCors(options =>
            {
                options.AddPolicy("MyPolicy",
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
        }