示例#1
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <CorsOptions>(Name);

            services.AddCors(cors =>
            {
                var allowedHeaders = options.AllowedHeaders ?? Enumerable.Empty <string>();
                var allowedMethods = options.AllowedMethods ?? Enumerable.Empty <string>();
                var allowedOrigins = options.AllowedOrigins ?? Enumerable.Empty <string>();
                var exposedHeaders = options.ExposedHeaders ?? Enumerable.Empty <string>();
                cors.AddPolicy("CorsPolicy", builder =>
                {
                    var origins = allowedOrigins.ToArray();
                    if (options.AllowCredentials && origins.FirstOrDefault() != "*")
                    {
                        builder.AllowCredentials();
                    }
                    else
                    {
                        builder.DisallowCredentials();
                    }

                    builder.WithHeaders(allowedHeaders.ToArray())
                    .WithMethods(allowedMethods.ToArray())
                    .WithOrigins(origins.ToArray())
                    .WithExposedHeaders(exposedHeaders.ToArray());
                });
            });
        }
示例#2
0
        public void Use(IApplicationBuilder app, IOptionsProvider optionsProvider)
        {
            var options     = optionsProvider.GetForExtension <SwaggerOptions>(Name);
            var routePrefix = string.IsNullOrWhiteSpace(options.RoutePrefix) ? "swagger" : options.RoutePrefix;

            app.UseStaticFiles()
            .UseSwagger(c => c.RouteTemplate = routePrefix + "/{documentName}/swagger.json");

            if (options.ReDocEnabled)
            {
                app.UseReDoc(c =>
                {
                    c.RoutePrefix = routePrefix;
                    c.SpecUrl     = $"{options.Name}/swagger.json";
                });

                return;
            }

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/{routePrefix}/{options.Name}/swagger.json", options.Title);
                c.RoutePrefix = routePrefix;
            });
        }
示例#3
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <CustomErrorsOptions>(Name);

            services.AddSingleton(options);
            services.AddScoped <ErrorHandlerMiddleware>();
        }
示例#4
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <TracingOptions>("tracing");

            services.AddOpenTracing();
            services.AddSingleton(options);
            if (options.UseEmptyTracer)
            {
                var defaultTracer = DefaultTracer.Create();
                services.AddSingleton(defaultTracer);
                return;
            }

            services.AddSingleton <ITracer>(sp =>
            {
                var loggerFactory = sp.GetRequiredService <ILoggerFactory>();

                var reporter = new RemoteReporter.Builder()
                               .WithSender(new UdpSender(options.UdpHost, options.UdpPort, options.MaxPacketSize))
                               .WithLoggerFactory(loggerFactory)
                               .Build();

                var sampler = GetSampler(options);

                var tracer = new Tracer.Builder(options.ServiceName)
                             .WithLoggerFactory(loggerFactory)
                             .WithReporter(reporter)
                             .WithSampler(sampler)
                             .Build();

                GlobalTracer.Register(tracer);

                return(tracer);
            });
        }
示例#5
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <RabbitMqOptions>(Name);

            services.AddSingleton(options);
            services.AddSingleton(sp =>
            {
                var connectionFactory = new ConnectionFactory
                {
                    HostName    = options.HostName,
                    Port        = options.Port,
                    VirtualHost = options.VirtualHost,
                    UserName    = options.Username,
                    Password    = options.Password,
                    RequestedConnectionTimeout = options.RequestedConnectionTimeout,
                    SocketReadTimeout          = options.SocketReadTimeout,
                    SocketWriteTimeout         = options.SocketWriteTimeout,
                    RequestedChannelMax        = options.RequestedChannelMax,
                    RequestedFrameMax          = options.RequestedFrameMax,
                    RequestedHeartbeat         = options.RequestedHeartbeat,
                    UseBackgroundThreadsForIO  = options.UseBackgroundThreadsForIO,
                    Ssl = options.Ssl is null
                        ? new SslOption()
                        : new SslOption(options.Ssl.ServerName, options.Ssl.CertificatePath, options.Ssl.Enabled),
                };

                return(connectionFactory.CreateConnection());
            });

            services.AddTransient <IRabbitMqClient, RabbitMqClient>();
            services.AddTransient <RabbitMqHandler>();
            services.AddSingleton <IContextBuilder, NullContextBuilder>();
        }
示例#6
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <TracingOptions>("tracing");

            services.AddOpenTracing();
            services.AddSingleton(options);
            if (options.UseEmptyTracer)
            {
                var defaultTracer = DefaultTracer.Create();
                services.AddSingleton(defaultTracer);
                return;
            }

            if (options.ExcludePaths is {})
示例#7
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <JwtOptions>(Name);

            services.AddAuthorization();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Key)),
                    ValidIssuer      = options.Issuer,
                    ValidIssuers     = options.Issuers,
                    ValidAudience    = options.Audience,
                    ValidAudiences   = options.Audiences,
                    ValidateIssuer   = options.ValidateIssuer,
                    ValidateAudience = options.ValidateAudience,
                    ValidateLifetime = options.ValidateLifetime
                };
            });
        }
示例#8
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <SwaggerOptions>(Name);

            services.AddSingleton(options);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(options.Name, new OpenApiInfo {
                    Title = options.Title, Version = options.Version
                });
                c.DocumentFilter <WebApiDocumentFilter>();
                if (options.IncludeSecurity)
                {
                    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description =
                            "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                        Name = "Authorization",
                        In   = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey
                    });
                }
            });
        }
示例#9
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <RabbitMqOptions>(Name);

            services.AddSingleton(options);
            services.AddSingleton(sp =>
            {
                var connectionFactory = new ConnectionFactory
                {
                    HostName    = options.Hostnames?.FirstOrDefault(),
                    Port        = options.Port,
                    VirtualHost = options.VirtualHost,
                    UserName    = options.Username,
                    Password    = options.Password,
                    RequestedConnectionTimeout = options.RequestedConnectionTimeout,
                    SocketReadTimeout          = options.SocketReadTimeout,
                    SocketWriteTimeout         = options.SocketWriteTimeout,
                    RequestedChannelMax        = options.RequestedChannelMax,
                    RequestedFrameMax          = options.RequestedFrameMax,
                    RequestedHeartbeat         = options.RequestedHeartbeat,
                    UseBackgroundThreadsForIO  = options.UseBackgroundThreadsForIO,
                    Ssl = options.Ssl is null
                        ? new SslOption()
                        : new SslOption(options.Ssl.ServerName, options.Ssl.CertificatePath, options.Ssl.Enabled),
                };

                var connection = connectionFactory.CreateConnection(options.ConnectionName);
                if (options.Exchange?.DeclareExchange != true)
                {
                    return(connection);
                }

                var ntradaOptions = optionsProvider.Get <NtradaOptions>();
                var exchanges     = ntradaOptions.Modules
                                    .SelectMany(m => m.Value.Routes)
                                    .Where(m => m.Use.Equals(Name, StringComparison.InvariantCultureIgnoreCase))
                                    .SelectMany(r => r.Config)
                                    .Where(c => c.Key.Equals("exchange", StringComparison.InvariantCultureIgnoreCase))
                                    .Distinct()
                                    .ToList();

                if (!exchanges.Any())
                {
                    return(connection);
                }

                var logger        = sp.GetService <ILogger <IConnection> >();
                var loggerEnabled = options.Logger?.Enabled == true;

                using (var channel = connection.CreateModel())
                {
                    foreach (var exchange in exchanges)
                    {
                        var name = exchange.Value;
                        var type = options.Exchange.Type;
                        if (loggerEnabled)
                        {
                            logger.LogInformation($"Declaring an exchange: '{name}', type: '{type}'.");
                        }

                        channel.ExchangeDeclare(name, type, options.Exchange.Durable, options.Exchange.AutoDelete);
                    }
                }

                return(connection);
            });

            services.AddTransient <IRabbitMqClient, RabbitMqClient>();
            services.AddTransient <RabbitMqHandler>();
            services.AddSingleton <IContextBuilder, NullContextBuilder>();
            services.AddSingleton <ISpanContextBuilder, NullSpanContextBuilder>();
        }
示例#10
0
        public void Add(IServiceCollection services, IOptionsProvider optionsProvider)
        {
            var options = optionsProvider.GetForExtension <JwtOptions>(Name);

            services.AddAuthorization();

            var tokenValidationParameters = new TokenValidationParameters
            {
                RequireAudience          = options.RequireAudience,
                ValidIssuer              = options.ValidIssuer,
                ValidIssuers             = options.ValidIssuers,
                ValidateActor            = options.ValidateActor,
                ValidAudience            = options.ValidAudience,
                ValidAudiences           = options.ValidAudiences,
                ValidateAudience         = options.ValidateAudience,
                ValidateIssuer           = options.ValidateIssuer,
                ValidateLifetime         = options.ValidateLifetime,
                ValidateTokenReplay      = options.ValidateTokenReplay,
                ValidateIssuerSigningKey = options.ValidateIssuerSigningKey,
                SaveSigninToken          = options.SaveSigninToken,
                RequireExpirationTime    = options.RequireExpirationTime,
                RequireSignedTokens      = options.RequireSignedTokens,
                ClockSkew = TimeSpan.Zero
            };

            if (!string.IsNullOrWhiteSpace(options.AuthenticationType))
            {
                tokenValidationParameters.AuthenticationType = options.AuthenticationType;
            }

            if (!string.IsNullOrWhiteSpace(options.IssuerSigningKey))
            {
                tokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(options.IssuerSigningKey));
            }

            if (!string.IsNullOrWhiteSpace(options.NameClaimType))
            {
                tokenValidationParameters.NameClaimType = options.NameClaimType;
            }

            if (!string.IsNullOrWhiteSpace(options.RoleClaimType))
            {
                tokenValidationParameters.RoleClaimType = options.RoleClaimType;
            }

            services.AddSingleton(tokenValidationParameters);

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.Authority                  = options.Authority;
                o.Audience                   = options.Audience;
                o.MetadataAddress            = options.MetadataAddress;
                o.SaveToken                  = options.SaveToken;
                o.RefreshOnIssuerKeyNotFound = options.RefreshOnIssuerKeyNotFound;
                o.RequireHttpsMetadata       = options.RequireHttpsMetadata;
                o.IncludeErrorDetails        = options.IncludeErrorDetails;
                o.TokenValidationParameters  = tokenValidationParameters;
                if (!string.IsNullOrWhiteSpace(options.Challenge))
                {
                    o.Challenge = options.Challenge;
                }
            });
        }