コード例 #1
0
ファイル: Startup.cs プロジェクト: ststeiger/CoreEncryption
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

            services.AddAuthentication(
                delegate(Microsoft.AspNetCore.Authentication.SharedAuthenticationOptions options)
            {
                // options.SignInScheme = "foo";
            }
                );

            // Add framework services.
            // services.AddMvc();
            services.AddMvc(
                delegate(Microsoft.AspNetCore.Mvc.MvcOptions config)
            {
                Microsoft.AspNetCore.Authorization.AuthorizationPolicy policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                                                                                .RequireAuthenticatedUser()
                                                                                // .AddRequirements( new NoBannedIPsRequirement(new HashSet<string>() { "127.0.0.1", "0.0.0.1" } ))
                                                                                .Build();

                config.Filters.Add(new Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter(policy));
            }
                );
        }
コード例 #2
0
        public static AuthorizationPolicy CreateResourceOwnerPolicy()
        {
            var policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                         .AddRequirements(new ResourceOwnerRequirement())
                         .Build();

            return(new AuthorizationPolicy(ResourceOwnerPolicyName, policy));
        }
コード例 #3
0
 /// <summary>
 /// 为所有Action添加权限验证,使用之后页面都会进行验证
 /// </summary>
 /// <param name="services"></param>
 /// <returns></returns>
 public static IServiceCollection AddAuthorizeFilter(this IServiceCollection services, IConfiguration configuration)
 {
     services.AddControllers(options => {
         var policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                      .RequireAuthenticatedUser()
                      .Build();
         //options.Filters.Add(new AuthorizeFilter(policy));//添加权限过滤器
         options.Filters.Add(new JhAuthorizationFilter(policy, configuration));
     });
     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.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin();
                });
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen();
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "CoFlows Quant Edition",
                    Description    = "CoFlows QE (Quant Edition) is a Containerized Polyglot Runtime that simplifies the development, hosting and deployment of powerful data-centric workflows. CoFlows enables developers to create rich Web-APIs with almost zero boiler plate and scheduled / reactive processes through a range of languages including CoreCLR (C#, F# and VB), JVM (Java and Scala), Python and Javascript. Furthermore, functions written in any of these languages can call each other within the same process with full interop.",
                    TermsOfService = new Uri("https://github.com/CoFlows/CoFlows-CE#license"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "CoFlows Community",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://www.coflows.com"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under MIT",
                        Url  = new Uri("https://github.com/CoFlows/CoFlows-CE#license"),
                    }
                });

                var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "CoFlows.Server.quant.lnx.xml");
                c.IncludeXmlComments(filePath);
            });

            services
            .AddMvc(option => option.EnableEndpointRouting = false)
            .AddNewtonsoftJson(options => {
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                options.SerializerSettings.Formatting       = Newtonsoft.Json.Formatting.Indented;
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            if (Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null)
            {
                services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = "coflows-ce",
                        ValidAudience    = "coflows-ce",
                        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey))
                    };
                })
                .AddAzureADB2CBearer(options => {
                    options.Instance             = Program.config["Server"]["OAuth"]["AzureAdB2C"]["Instance"].ToString();
                    options.ClientId             = Program.config["Server"]["OAuth"]["AzureAdB2C"]["ClientId"].ToString();
                    options.Domain               = Program.config["Server"]["OAuth"]["AzureAdB2C"]["Domain"].ToString();
                    options.SignUpSignInPolicyId = Program.config["Server"]["OAuth"]["AzureAdB2C"]["SignUpSignInPolicyId"].ToString();
                });

                services.AddAuthorization(options =>
                {
                    var defaultAuthorizationPolicyBuilder =
                        new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder(
                            JwtBearerDefaults.AuthenticationScheme,
                            AzureADB2CDefaults.BearerAuthenticationScheme)
                        .RequireAuthenticatedUser();

                    options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
                });
            }
            else
            {
                services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = "coflows-ce",
                        ValidAudience    = "coflows-ce",
                        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey))
                    };
                });
            }



            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <RTDSocketManager>();

            if (Program.hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(Program.letsEncryptEmail))
            {
                services.AddFluffySpoonLetsEncrypt(new LetsEncryptOptions()
                {
                    Email      = Program.letsEncryptEmail,
                    UseStaging = Program.letsEncryptStaging,
                    Domains    = new[] { Program.hostName },
                    TimeUntilExpiryBeforeRenewal = TimeSpan.FromDays(30),
                    CertificateSigningRequest    = new CsrInfo()
                    {
                        CountryName      = "Multiverse",
                        Locality         = "Universe",
                        Organization     = "GetStuffDone",
                        OrganizationUnit = "ImportantStuffDone",
                        State            = "MilkyWay"
                    }
                });

                services.AddFluffySpoonLetsEncryptCertificatePersistence(
                    async(key, bytes) => {
                    var mKey = "---LetsEncrypt--" + Program.hostName + "." + Program.letsEncryptEmail + "." + (Program.letsEncryptStaging ? "Staging" : "Production") + ".certificate_" + key;
                    var m    = QuantApp.Kernel.M.Base(mKey);

                    var resList = m[x => QuantApp.Kernel.M.V <string>(x, "Key") == key.ToString()];
                    if (resList != null && resList.Count > 0)
                    {
                        var strData = System.Convert.ToBase64String(bytes);
                        m.Exchange(resList[0], new Certificate()
                        {
                            Key = key.ToString(), Data = strData
                        });

                        Console.WriteLine("LetsEncrypt certificate UPDATED...");
                    }
                    else
                    {
                        var strData = System.Convert.ToBase64String(bytes);
                        m          += new Certificate()
                        {
                            Key = key.ToString(), Data = strData
                        };
                        Console.WriteLine("LetsEncrypt certificate CREATED...");
                    }
                    m.Save();
                },
                    async(key) => {
                    var mKey = "---LetsEncrypt--" + Program.hostName + "." + Program.letsEncryptEmail + "." + (Program.letsEncryptStaging ? "Staging" : "Production") + ".certificate_" + key;

                    try
                    {
                        var m       = QuantApp.Kernel.M.Base(mKey);
                        var resList = m[x => QuantApp.Kernel.M.V <string>(x, "Key") == key.ToString()];
                        if (resList != null && resList.Count > 0)
                        {
                            var data  = QuantApp.Kernel.M.V <string>(resList[0], "Data");
                            var bytes = System.Convert.FromBase64String(data);
                            Console.WriteLine("LetsEncrypt found certificate...");
                            return(bytes);
                        }

                        Console.WriteLine("LetsEncrypt didn't find a certificate, attempting to create one...");

                        return(null);
                    }
                    catch (System.Exception e)
                    {
                        return(null);
                    }
                });
                services.AddFluffySpoonLetsEncryptFileChallengePersistence();
            }
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(
                x => x.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")).UseLazyLoadingProxies());

            IdentityBuilder builder = services.AddIdentityCore <User>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 4;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII
                                                                        .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            services.AddMvc(options =>
            {
                var policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling =
                                   Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddSwaggerGen(); services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "API",
                    Description = "A simple example ASP.NET Core Web API",
                    //TermsOfService = new Uri("https://example.com/terms"),
                    //Contact = new OpenApiContact
                    //{
                    //    Name = "Shayne Boyer",
                    //    Email = string.Empty,
                    //    Url = new Uri("https://twitter.com/spboyer"),
                    //},
                    //License = new OpenApiLicense
                    //{
                    //    Name = "Use under LICX",
                    //    Url = new Uri("https://example.com/license"),
                    //}
                });
            });
            services.AddScoped <IRepository, VotacaoAlterData.Repository.Repository>();
            services.AddAutoMapper(typeof(Startup));
            services.AddCors();
            services.AddControllersWithViews();
        }
コード例 #6
0
ファイル: Startup.cs プロジェクト: Anny777/NebulaApiMigration
        /// <summary>
        /// ConfigureServices.
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));
            services.ConfigureEagerly <NebulaApiOptions>(this.configuration);
            services.ConfigureEagerly <NebulaAuthorizationOptions>(this.configuration);
            services.AddScoped <ApplicationContext>();

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "nebula",
                    ValidAudience    = "nebula",
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(this.configuration.GetSection("NebulaAuthorizationOptions:SymmetricSecurityKey")
                                               .Value)),
                };
            });

            services.AddCors();

            services.AddMvc(config =>
            {
                config.EnableEndpointRouting = false;
                var policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationContext>().AddDefaultTokenProviders();

            services.AddDbContext <ApplicationContext>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Nebula API", Version = "v1"
                });

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

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });
        }