used framework provides extension method to add IHttpContextAccessor in the DI container
This commit is contained in:
parent
e70b2b2950
commit
23d3e60c9e
@ -1,7 +1,6 @@
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
|
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
|
||||||
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters;
|
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters;
|
||||||
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure;
|
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure;
|
||||||
@ -19,166 +18,166 @@ using System.Net.Http;
|
|||||||
|
|
||||||
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator
|
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator
|
||||||
{
|
{
|
||||||
public class Startup
|
public class Startup
|
||||||
{
|
{
|
||||||
public Startup(IConfiguration configuration)
|
public Startup(IConfiguration configuration)
|
||||||
{
|
{
|
||||||
Configuration = configuration;
|
Configuration = configuration;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IConfiguration Configuration { get; }
|
public IConfiguration Configuration { get; }
|
||||||
|
|
||||||
// This method gets called by the runtime. 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)
|
public void ConfigureServices(IServiceCollection services)
|
||||||
{
|
{
|
||||||
services.AddCustomMvc(Configuration)
|
services.AddCustomMvc(Configuration)
|
||||||
.AddCustomAuthentication(Configuration)
|
.AddCustomAuthentication(Configuration)
|
||||||
.AddHttpServices();
|
.AddHttpServices();
|
||||||
}
|
}
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||||
{
|
{
|
||||||
var pathBase = Configuration["PATH_BASE"];
|
var pathBase = Configuration["PATH_BASE"];
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(pathBase))
|
if (!string.IsNullOrEmpty(pathBase))
|
||||||
{
|
{
|
||||||
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
|
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
|
||||||
app.UsePathBase(pathBase);
|
app.UsePathBase(pathBase);
|
||||||
}
|
}
|
||||||
|
|
||||||
app.UseCors("CorsPolicy");
|
app.UseCors("CorsPolicy");
|
||||||
|
|
||||||
if (env.IsDevelopment())
|
if (env.IsDevelopment())
|
||||||
{
|
{
|
||||||
app.UseDeveloperExceptionPage();
|
app.UseDeveloperExceptionPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
|
|
||||||
app.UseMvc();
|
app.UseMvc();
|
||||||
|
|
||||||
app.UseSwagger().UseSwaggerUI(c =>
|
app.UseSwagger().UseSwaggerUI(c =>
|
||||||
{
|
{
|
||||||
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1");
|
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1");
|
||||||
c.ConfigureOAuth2("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI");
|
c.ConfigureOAuth2("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ServiceCollectionExtensions
|
public static class ServiceCollectionExtensions
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration)
|
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services.AddOptions();
|
services.AddOptions();
|
||||||
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
|
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
|
||||||
|
|
||||||
services.AddMvc().SetCompatibilityVersion(AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
|
services.AddMvc().SetCompatibilityVersion(AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
|
||||||
|
|
||||||
services.AddSwaggerGen(options =>
|
services.AddSwaggerGen(options =>
|
||||||
{
|
{
|
||||||
options.DescribeAllEnumsAsStrings();
|
options.DescribeAllEnumsAsStrings();
|
||||||
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
|
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
|
||||||
{
|
{
|
||||||
Title = "Shopping Aggregator for Mobile Clients",
|
Title = "Shopping Aggregator for Mobile Clients",
|
||||||
Version = "v1",
|
Version = "v1",
|
||||||
Description = "Shopping Aggregator for Mobile Clients",
|
Description = "Shopping Aggregator for Mobile Clients",
|
||||||
TermsOfService = "Terms Of Service"
|
TermsOfService = "Terms Of Service"
|
||||||
});
|
});
|
||||||
|
|
||||||
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
|
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
|
||||||
{
|
{
|
||||||
Type = "oauth2",
|
Type = "oauth2",
|
||||||
Flow = "implicit",
|
Flow = "implicit",
|
||||||
AuthorizationUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
|
AuthorizationUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
|
||||||
TokenUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
|
TokenUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
|
||||||
Scopes = new Dictionary<string, string>()
|
Scopes = new Dictionary<string, string>()
|
||||||
{
|
{
|
||||||
{ "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" }
|
{ "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
options.OperationFilter<AuthorizeCheckOperationFilter>();
|
options.OperationFilter<AuthorizeCheckOperationFilter>();
|
||||||
});
|
});
|
||||||
|
|
||||||
services.AddCors(options =>
|
services.AddCors(options =>
|
||||||
{
|
{
|
||||||
options.AddPolicy("CorsPolicy",
|
options.AddPolicy("CorsPolicy",
|
||||||
builder => builder.AllowAnyOrigin()
|
builder => builder.AllowAnyOrigin()
|
||||||
.AllowAnyMethod()
|
.AllowAnyMethod()
|
||||||
.AllowAnyHeader()
|
.AllowAnyHeader()
|
||||||
.AllowCredentials());
|
.AllowCredentials());
|
||||||
});
|
});
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
|
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
||||||
var identityUrl = configuration.GetValue<string>("urls:identity");
|
var identityUrl = configuration.GetValue<string>("urls:identity");
|
||||||
services.AddAuthentication(options =>
|
services.AddAuthentication(options =>
|
||||||
{
|
{
|
||||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
|
||||||
}).AddJwtBearer(options =>
|
}).AddJwtBearer(options =>
|
||||||
{
|
{
|
||||||
options.Authority = identityUrl;
|
options.Authority = identityUrl;
|
||||||
options.RequireHttpsMetadata = false;
|
options.RequireHttpsMetadata = false;
|
||||||
options.Audience = "mobileshoppingagg";
|
options.Audience = "mobileshoppingagg";
|
||||||
options.Events = new JwtBearerEvents()
|
options.Events = new JwtBearerEvents()
|
||||||
{
|
{
|
||||||
OnAuthenticationFailed = async ctx =>
|
OnAuthenticationFailed = async ctx =>
|
||||||
{
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
},
|
},
|
||||||
OnTokenValidated = async ctx =>
|
OnTokenValidated = async ctx =>
|
||||||
{
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
public static IServiceCollection AddHttpServices(this IServiceCollection services)
|
public static IServiceCollection AddHttpServices(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
//register delegating handlers
|
//register delegating handlers
|
||||||
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
|
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
|
||||||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
services.AddHttpContextAccessor();
|
||||||
|
|
||||||
//register http services
|
//register http services
|
||||||
services.AddHttpClient<IBasketService, BasketService>()
|
services.AddHttpClient<IBasketService, BasketService>()
|
||||||
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
|
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
|
||||||
.AddPolicyHandler(GetRetryPolicy())
|
.AddPolicyHandler(GetRetryPolicy())
|
||||||
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
||||||
|
|
||||||
services.AddHttpClient<ICatalogService, CatalogService>()
|
services.AddHttpClient<ICatalogService, CatalogService>()
|
||||||
.AddPolicyHandler(GetRetryPolicy())
|
.AddPolicyHandler(GetRetryPolicy())
|
||||||
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
||||||
|
|
||||||
services.AddHttpClient<IOrderApiClient, OrderApiClient>()
|
services.AddHttpClient<IOrderApiClient, OrderApiClient>()
|
||||||
.AddPolicyHandler(GetRetryPolicy())
|
.AddPolicyHandler(GetRetryPolicy())
|
||||||
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
.AddPolicyHandler(GetCircuitBreakerPolicy());
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
|
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
|
||||||
{
|
{
|
||||||
return HttpPolicyExtensions
|
return HttpPolicyExtensions
|
||||||
.HandleTransientHttpError()
|
.HandleTransientHttpError()
|
||||||
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
|
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||||
.WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
|
.WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
|
||||||
|
|
||||||
}
|
}
|
||||||
static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
|
static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
|
||||||
{
|
{
|
||||||
return HttpPolicyExtensions
|
return HttpPolicyExtensions
|
||||||
.HandleTransientHttpError()
|
.HandleTransientHttpError()
|
||||||
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
|
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user