182 lines
7.0 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Authentication.JwtBearer;
2018-02-27 14:32:25 +01:00
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Config;
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters;
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Infrastructure;
2018-02-27 14:32:25 +01:00
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.Extensions.Http;
using Polly.Timeout;
2018-02-27 14:32:25 +01:00
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
2018-02-27 14:32:25 +01:00
namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCustomMvc(Configuration)
.AddCustomAuthentication(Configuration)
.AddApplicationServices();
}
// 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)
{
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
app.UsePathBase(pathBase);
}
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
app.UseSwagger().UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1");
//c.ConfigureOAuth2("Microsoft.eShopOnContainers.Web.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI");
});
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var identityUrl = configuration.GetValue<string>("urls:identity");
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = "webshoppingagg";
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = async ctx =>
{
int i = 0;
},
OnTokenValidated = async ctx =>
{
int i = 0;
}
};
});
2018-02-27 14:32:25 +01:00
return services;
}
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration)
{
2018-02-27 14:32:25 +01:00
services.AddOptions();
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
2018-02-27 14:32:25 +01:00
services.AddMvc();
services.AddSwaggerGen(options =>
{
options.DescribeAllEnumsAsStrings();
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
2018-02-27 17:29:37 +01:00
Title = "Shopping Aggregator for Web Clients",
2018-02-27 14:32:25 +01:00
Version = "v1",
2018-02-27 17:29:37 +01:00
Description = "Shopping Aggregator for Web Clients",
2018-02-27 14:32:25 +01:00
TermsOfService = "Terms Of Service"
});
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
TokenUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
2018-02-27 14:32:25 +01:00
Scopes = new Dictionary<string, string>()
{
2018-02-27 17:29:37 +01:00
{ "webshoppingagg", "Shopping Aggregator for Web Clients" }
2018-02-27 14:32:25 +01:00
}
});
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
return services;
2018-02-27 14:32:25 +01:00
}
public static IServiceCollection AddApplicationServices(this IServiceCollection services)
2018-02-27 14:32:25 +01:00
{
//register delegating handlers
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2018-02-27 14:32:25 +01:00
//register http services
var retriesWithExponentialBackoff = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.OrResult(message => message.StatusCode == System.Net.HttpStatusCode.NotFound)
2018-05-22 18:19:13 +02:00
.WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
2018-02-27 14:32:25 +01:00
var circuitBreaker = HttpPolicyExtensions
.HandleTransientHttpError()
2018-05-22 18:19:13 +02:00
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
2018-02-27 14:32:25 +01:00
services.AddHttpClient<IBasketService, BasketService>()
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddPolicyHandler(retriesWithExponentialBackoff)
.AddPolicyHandler(circuitBreaker);
2018-02-27 14:32:25 +01:00
services.AddHttpClient<ICatalogService, CatalogService>()
.AddPolicyHandler(retriesWithExponentialBackoff)
.AddPolicyHandler(circuitBreaker);
2018-02-27 14:32:25 +01:00
services.AddHttpClient<IOrderApiClient, OrderApiClient>()
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
.AddPolicyHandler(retriesWithExponentialBackoff)
.AddPolicyHandler(circuitBreaker);
2018-02-27 14:32:25 +01:00
return services;
2018-02-27 14:32:25 +01:00
}
}
}