コード例 #1
0
ファイル: Startup.cs プロジェクト: Bravo-Two-Six/wegan
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
            var databaseUri = new Uri(databaseUrl);
            var userInfo    = databaseUri.UserInfo.Split(':');

            var builder = new NpgsqlConnectionStringBuilder
            {
                Host     = databaseUri.Host,
                Port     = databaseUri.Port,
                Username = userInfo[0],
                Password = userInfo[1],
                Database = databaseUri.LocalPath.TrimStart('/'),
                SslMode  = SslMode.Require,
                TrustServerCertificate = true
            };

            services.AddDbContext <AppIdentityDbContext>(options =>
                                                         options.UseNpgsql(builder.ConnectionString));
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <AppIdentityDbContext>();
            services.AddControllersWithViews();
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
            }));
        }
コード例 #2
0
        // Use this method to add services to the container.
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var jwtTokenConfig = Configuration.GetSection("jwtTokenConfig").Get <JwtTokenConfig>();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtTokenConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
                    ValidAudience            = jwtTokenConfig.Audience,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };
            });

            services.AddMvc(option =>
            {
                option.FormatterMappings.SetMediaTypeMappingForFormat("octet-stream", MediaTypeHeaderValue.Parse("application/octet-stream"));
            }).AddControllersAsServices();

            var builder = new NpgsqlConnectionStringBuilder
            {
                Username           = "******",
                Password           = "******",
                Host               = "localhost",
                Port               = 5432,
                Database           = "postgres",
                IntegratedSecurity = true,
                Pooling            = true
            };

            var connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING")
                                   ?? Configuration.GetConnectionString("PostgreSQLConnectionLocal");

            services
            // .AddEntityFrameworkNpgsql() Depricated
            .AddDbContext <DomainContext>(options => options.UseNpgsql(connectionString, builder => builder.MigrationsAssembly("ICS.Domain")) /*, contextLifetime: ServiceLifetime.Transient, optionsLifetime: ServiceLifetime.Transient*/)
            .AddDbContext <SystemContext>(options => options.UseNpgsql(connectionString, builder => builder.MigrationsAssembly("ICS.Domain")));

            /*//services.AddEntityFrameworkProxies();
             * services.AddEntityFrameworkNpgsql()
             *  .AddDbContext<DomainContext>(opt =>
             *  {
             *      opt.UseNpgsql(connectionString);
             *      //opt.UseLazyLoadingProxies(true);
             *  })
             *  .AddDbContext<SystemContext>(opt =>
             *  {
             *      opt.UseNpgsql(connectionString);
             *      //opt.UseLazyLoadingProxies(true);
             *  });*/

            // Web API middleware which will register all the controllers (classes derived from ControllerBase)
            /// <see cref="https://medium.com/imaginelearning/asp-net-core-3-1-microservice-quick-start-c0c2f4d6c7fa"/>
            services.AddControllers().AddNewtonsoftJson();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddSwaggerGen(c =>
            {
                var securityScheme = new OpenApiSecurityScheme
                {
                    Name         = "JWT Authentication",
                    Description  = "Enter JWT Bearer token **_only_**",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.Http,
                    Scheme       = "bearer", // must be lower case
                    BearerFormat = "JWT",
                    Reference    = new OpenApiReference
                    {
                        Id   = JwtBearerDefaults.AuthenticationScheme,
                        Type = ReferenceType.SecurityScheme
                    }
                };

                c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { securityScheme, new string[] { } }
                });

                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "JWT Auth Demo", Version = "v1"
                });
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });
        }
コード例 #3
0
ファイル: Startup.cs プロジェクト: kabylan/iad-sbran
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var jwtTokenConfig = Configuration.GetSection("jwtTokenConfig").Get <JwtTokenConfig>();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = jwtTokenConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
                    ValidAudience            = jwtTokenConfig.Audience,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.FromMinutes(1)
                };

                x.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/chattinghub")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddMvc(option =>
            {
                option.FormatterMappings.SetMediaTypeMappingForFormat("octet-stream", MediaTypeHeaderValue.Parse("application/octet-stream"));
            }).AddControllersAsServices();

            var builder = new NpgsqlConnectionStringBuilder
            {
                Username           = "******",
                Password           = "******",
                Host               = "localhost",
                Port               = 5432,
                Database           = "postgres",
                IntegratedSecurity = true,
                Pooling            = true
            };

            var connectionString = Configuration.GetConnectionString("PostgreSQLConnection");

            services
            // .AddEntityFrameworkNpgsql() Depricated
            .AddDbContext <DomainContext>(options => options.UseNpgsql(connectionString) /*, contextLifetime: ServiceLifetime.Transient, optionsLifetime: ServiceLifetime.Transient*/)
            .AddDbContext <SystemContext>(options => options.UseNpgsql(connectionString /*, builder => builder.MigrationsAssembly("ICS.Domain")*/));

            /*//services.AddEntityFrameworkProxies();
             * services.AddEntityFrameworkNpgsql()
             *  .AddDbContext<DomainContext>(opt =>
             *  {
             *      opt.UseNpgsql(connectionString);
             *      //opt.UseLazyLoadingProxies(true);
             *  })
             *  .AddDbContext<SystemContext>(opt =>
             *  {
             *      opt.UseNpgsql(connectionString);
             *      //opt.UseLazyLoadingProxies(true);
             *  });*/

            // Web API middleware which will register all the controllers (classes derived from ControllerBase)
            /// <see cref="https://medium.com/imaginelearning/asp-net-core-3-1-microservice-quick-start-c0c2f4d6c7fa"/>
            services.AddControllers().AddNewtonsoftJson();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });


            services.AddSwagger("Invitation control service (ICS)", openApiSettings =>
            {
                /*
                 * openApiSettings.OperationProcessors.Add(new AddHeaderProcessor(XCreatorId, true, "”никальный идентификатор сервиса"));
                 *
                 * openApiSettings.AddSwaggerTypeMappersInheritedFrom(
                 *  typeof(StringValueObject),
                 *  objectType => new PrimitiveTypeMapper(objectType, jsonSchema => jsonSchema.Type = JsonObjectType.String));
                 */
            });

            /*
             * services.AddSwaggerGen(c =>
             * {
             *  var securityScheme = new OpenApiSecurityScheme
             *  {
             *      Name = "JWT Authentication",
             *      Description = "Enter JWT Bearer token **_only_**",
             *      In = ParameterLocation.Header,
             *      Type = SecuritySchemeType.Http,
             *      Scheme = "bearer", // must be lower case
             *      BearerFormat = "JWT",
             *      Reference = new OpenApiReference
             *      {
             *          Id = JwtBearerDefaults.AuthenticationScheme,
             *          Type = ReferenceType.SecurityScheme
             *      }
             *  };
             *
             *  c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
             *  c.AddSecurityRequirement(new OpenApiSecurityRequirement
             *  {
             *      {securityScheme, new string[] { }}
             *  });
             *
             *  c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT Auth Demo", Version = "v1" });
             * });
             */

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

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins("https://localhost:44343/");
            }));


            services.AddSingleton <IUserIdProvider, CustomUserIdProvider>();
            services.AddSignalR();
            services.AddSignalRCore();
        }