* Included globalusing file for webhookclient * Included file scope namespaces for Webhookclient * Updated packages in WebHookClient projectpull/1785/head
@ -1,37 +1,28 @@ | |||
using Microsoft.AspNetCore.Authentication; | |||
using Microsoft.AspNetCore.Authentication.Cookies; | |||
using Microsoft.AspNetCore.Authentication.OpenIdConnect; | |||
using Microsoft.AspNetCore.Authorization; | |||
using Microsoft.AspNetCore.Mvc; | |||
using System.Security.Claims; | |||
using System.Threading.Tasks; | |||
namespace WebhookClient.Controllers; | |||
namespace WebhookClient.Controllers | |||
[Authorize] | |||
public class AccountController : Controller | |||
{ | |||
[Authorize] | |||
public class AccountController : Controller | |||
public async Task<IActionResult> SignIn(string returnUrl) | |||
{ | |||
public async Task<IActionResult> SignIn(string returnUrl) | |||
{ | |||
var user = User as ClaimsPrincipal; | |||
var token = await HttpContext.GetTokenAsync("access_token"); | |||
var user = User as ClaimsPrincipal; | |||
if (token != null) | |||
{ | |||
ViewData["access_token"] = token; | |||
} | |||
return RedirectToPage("/Index"); | |||
} | |||
var token = await HttpContext.GetTokenAsync("access_token"); | |||
public async Task<IActionResult> Signout() | |||
if (token != null) | |||
{ | |||
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); | |||
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); | |||
var homeUrl = Url.Page("/Index"); | |||
return new SignOutResult(OpenIdConnectDefaults.AuthenticationScheme, | |||
new AuthenticationProperties { RedirectUri = homeUrl }); | |||
ViewData["access_token"] = token; | |||
} | |||
return RedirectToPage("/Index"); | |||
} | |||
public async Task<IActionResult> Signout() | |||
{ | |||
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); | |||
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); | |||
var homeUrl = Url.Page("/Index"); | |||
return new SignOutResult(OpenIdConnectDefaults.AuthenticationScheme, | |||
new AuthenticationProperties { RedirectUri = homeUrl }); | |||
} | |||
} |
@ -1,53 +1,44 @@ | |||
using Microsoft.AspNetCore.Mvc; | |||
using Microsoft.Extensions.Logging; | |||
using Microsoft.Extensions.Options; | |||
using System.Linq; | |||
using System.Threading.Tasks; | |||
using WebhookClient.Models; | |||
using WebhookClient.Services; | |||
namespace WebhookClient.Controllers; | |||
namespace WebhookClient.Controllers | |||
[ApiController] | |||
[Route("webhook-received")] | |||
public class WebhooksReceivedController : Controller | |||
{ | |||
[ApiController] | |||
[Route("webhook-received")] | |||
public class WebhooksReceivedController : Controller | |||
{ | |||
private readonly Settings _settings; | |||
private readonly ILogger _logger; | |||
private readonly IHooksRepository _hooksRepository; | |||
private readonly Settings _settings; | |||
private readonly ILogger _logger; | |||
private readonly IHooksRepository _hooksRepository; | |||
public WebhooksReceivedController(IOptions<Settings> settings, ILogger<WebhooksReceivedController> logger, IHooksRepository hooksRepository) | |||
{ | |||
_settings = settings.Value; | |||
_logger = logger; | |||
_hooksRepository = hooksRepository; | |||
} | |||
public WebhooksReceivedController(IOptions<Settings> settings, ILogger<WebhooksReceivedController> logger, IHooksRepository hooksRepository) | |||
{ | |||
_settings = settings.Value; | |||
_logger = logger; | |||
_hooksRepository = hooksRepository; | |||
} | |||
[HttpPost] | |||
public async Task<IActionResult> NewWebhook(WebhookData hook) | |||
{ | |||
var header = Request.Headers[HeaderNames.WebHookCheckHeader]; | |||
var token = header.FirstOrDefault(); | |||
[HttpPost] | |||
public async Task<IActionResult> NewWebhook(WebhookData hook) | |||
{ | |||
var header = Request.Headers[HeaderNames.WebHookCheckHeader]; | |||
var token = header.FirstOrDefault(); | |||
_logger.LogInformation("Received hook with token {Token}. My token is {MyToken}. Token validation is set to {ValidateToken}", token, _settings.Token, _settings.ValidateToken); | |||
_logger.LogInformation("Received hook with token {Token}. My token is {MyToken}. Token validation is set to {ValidateToken}", token, _settings.Token, _settings.ValidateToken); | |||
if (!_settings.ValidateToken || _settings.Token == token) | |||
if (!_settings.ValidateToken || _settings.Token == token) | |||
{ | |||
_logger.LogInformation("Received hook is going to be processed"); | |||
var newHook = new WebHookReceived() | |||
{ | |||
_logger.LogInformation("Received hook is going to be processed"); | |||
var newHook = new WebHookReceived() | |||
{ | |||
Data = hook.Payload, | |||
When = hook.When, | |||
Token = token | |||
}; | |||
await _hooksRepository.AddNew(newHook); | |||
_logger.LogInformation("Received hook was processed."); | |||
return Ok(newHook); | |||
} | |||
_logger.LogInformation("Received hook is NOT processed - Bad Request returned."); | |||
return BadRequest(); | |||
Data = hook.Payload, | |||
When = hook.When, | |||
Token = token | |||
}; | |||
await _hooksRepository.AddNew(newHook); | |||
_logger.LogInformation("Received hook was processed."); | |||
return Ok(newHook); | |||
} | |||
_logger.LogInformation("Received hook is NOT processed - Bad Request returned."); | |||
return BadRequest(); | |||
} | |||
} |
@ -0,0 +1,27 @@ | |||
global using Microsoft.AspNetCore.Authentication; | |||
global using Microsoft.AspNetCore.Authentication.Cookies; | |||
global using Microsoft.AspNetCore.Authentication.OpenIdConnect; | |||
global using Microsoft.AspNetCore.Authorization; | |||
global using Microsoft.AspNetCore.Mvc; | |||
global using System.Security.Claims; | |||
global using System.Threading.Tasks; | |||
global using Microsoft.Extensions.Logging; | |||
global using Microsoft.Extensions.Options; | |||
global using System.Linq; | |||
global using WebhookClient.Models; | |||
global using WebhookClient.Services; | |||
global using System; | |||
global using System.Collections.Generic; | |||
global using System.Net.Http; | |||
global using System.Text.Json; | |||
global using Microsoft.AspNetCore.Http; | |||
global using System.Net.Http.Headers; | |||
global using System.Threading; | |||
global using Microsoft.AspNetCore; | |||
global using Microsoft.AspNetCore.Hosting; | |||
global using WebhookClient; | |||
global using Microsoft.AspNetCore.Builder; | |||
global using Microsoft.Extensions.Configuration; | |||
global using Microsoft.Extensions.DependencyInjection; | |||
global using Microsoft.Extensions.Hosting; | |||
global using System.Net; |
@ -1,7 +1,6 @@ | |||
namespace WebhookClient | |||
namespace WebhookClient; | |||
static class HeaderNames | |||
{ | |||
static class HeaderNames | |||
{ | |||
public const string WebHookCheckHeader = "X-eshop-whtoken"; | |||
} | |||
public const string WebHookCheckHeader = "X-eshop-whtoken"; | |||
} |
@ -1,49 +1,40 @@ | |||
using Microsoft.AspNetCore.Authentication; | |||
using Microsoft.AspNetCore.Http; | |||
using System.Collections.Generic; | |||
using System.Net.Http; | |||
using System.Net.Http.Headers; | |||
using System.Threading; | |||
using System.Threading.Tasks; | |||
namespace WebhookClient | |||
namespace WebhookClient; | |||
public class HttpClientAuthorizationDelegatingHandler | |||
: DelegatingHandler | |||
{ | |||
public class HttpClientAuthorizationDelegatingHandler | |||
: DelegatingHandler | |||
private readonly IHttpContextAccessor _httpContextAccessor; | |||
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor) | |||
{ | |||
private readonly IHttpContextAccessor _httpContextAccessor; | |||
_httpContextAccessor = httpContextAccessor; | |||
} | |||
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor) | |||
{ | |||
_httpContextAccessor = httpContextAccessor; | |||
} | |||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |||
{ | |||
var authorizationHeader = _httpContextAccessor.HttpContext | |||
.Request.Headers["Authorization"]; | |||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |||
if (!string.IsNullOrEmpty(authorizationHeader)) | |||
{ | |||
var authorizationHeader = _httpContextAccessor.HttpContext | |||
.Request.Headers["Authorization"]; | |||
if (!string.IsNullOrEmpty(authorizationHeader)) | |||
{ | |||
request.Headers.Add("Authorization", new List<string>() { authorizationHeader }); | |||
} | |||
var token = await GetToken(); | |||
request.Headers.Add("Authorization", new List<string>() { authorizationHeader }); | |||
} | |||
if (token != null) | |||
{ | |||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); | |||
} | |||
var token = await GetToken(); | |||
return await base.SendAsync(request, cancellationToken); | |||
if (token != null) | |||
{ | |||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); | |||
} | |||
async Task<string> GetToken() | |||
{ | |||
const string ACCESS_TOKEN = "access_token"; | |||
return await base.SendAsync(request, cancellationToken); | |||
} | |||
return await _httpContextAccessor.HttpContext | |||
.GetTokenAsync(ACCESS_TOKEN); | |||
} | |||
async Task<string> GetToken() | |||
{ | |||
const string ACCESS_TOKEN = "access_token"; | |||
return await _httpContextAccessor.HttpContext | |||
.GetTokenAsync(ACCESS_TOKEN); | |||
} | |||
} |
@ -1,13 +1,10 @@ | |||
using System; | |||
namespace WebhookClient.Models; | |||
namespace WebhookClient.Models | |||
public class WebHookReceived | |||
{ | |||
public class WebHookReceived | |||
{ | |||
public DateTime When { get; set; } | |||
public DateTime When { get; set; } | |||
public string Data { get; set; } | |||
public string Data { get; set; } | |||
public string Token { get; set; } | |||
} | |||
public string Token { get; set; } | |||
} |
@ -1,13 +1,10 @@ | |||
using System; | |||
namespace WebhookClient.Models; | |||
namespace WebhookClient.Models | |||
public class WebhookData | |||
{ | |||
public class WebhookData | |||
{ | |||
public DateTime When { get; set; } | |||
public DateTime When { get; set; } | |||
public string Payload { get; set; } | |||
public string Payload { get; set; } | |||
public string Type { get; set; } | |||
} | |||
public string Type { get; set; } | |||
} |
@ -1,11 +1,8 @@ | |||
using System; | |||
namespace WebhookClient.Models; | |||
namespace WebhookClient.Models | |||
public class WebhookResponse | |||
{ | |||
public class WebhookResponse | |||
{ | |||
public DateTime Date { get; set; } | |||
public string DestUrl { get; set; } | |||
public string Token { get; set; } | |||
} | |||
public DateTime Date { get; set; } | |||
public string DestUrl { get; set; } | |||
public string Token { get; set; } | |||
} |
@ -1,10 +1,9 @@ | |||
namespace WebhookClient.Models | |||
namespace WebhookClient.Models; | |||
public class WebhookSubscriptionRequest | |||
{ | |||
public class WebhookSubscriptionRequest | |||
{ | |||
public string Url { get; set; } | |||
public string Token { get; set; } | |||
public string Event { get; set; } | |||
public string GrantUrl { get; set; } | |||
} | |||
public string Url { get; set; } | |||
public string Token { get; set; } | |||
public string Event { get; set; } | |||
public string GrantUrl { get; set; } | |||
} |
@ -1,12 +1,7 @@ | |||
using System.Collections.Generic; | |||
using System.Threading.Tasks; | |||
using WebhookClient.Models; | |||
namespace WebhookClient.Services; | |||
namespace WebhookClient.Services | |||
public interface IHooksRepository | |||
{ | |||
public interface IHooksRepository | |||
{ | |||
Task<IEnumerable<WebHookReceived>> GetAll(); | |||
Task AddNew(WebHookReceived hook); | |||
} | |||
Task<IEnumerable<WebHookReceived>> GetAll(); | |||
Task AddNew(WebHookReceived hook); | |||
} |
@ -1,11 +1,6 @@ | |||
using System.Collections.Generic; | |||
using System.Threading.Tasks; | |||
using WebhookClient.Models; | |||
namespace WebhookClient.Services; | |||
namespace WebhookClient.Services | |||
public interface IWebhooksClient | |||
{ | |||
public interface IWebhooksClient | |||
{ | |||
Task<IEnumerable<WebhookResponse>> LoadWebhooks(); | |||
} | |||
Task<IEnumerable<WebhookResponse>> LoadWebhooks(); | |||
} |
@ -1,25 +1,19 @@ | |||
using System.Collections.Generic; | |||
using System.Linq; | |||
using System.Threading.Tasks; | |||
using WebhookClient.Models; | |||
namespace WebhookClient.Services; | |||
namespace WebhookClient.Services | |||
public class InMemoryHooksRepository : IHooksRepository | |||
{ | |||
public class InMemoryHooksRepository : IHooksRepository | |||
{ | |||
private readonly List<WebHookReceived> _data; | |||
private readonly List<WebHookReceived> _data; | |||
public InMemoryHooksRepository() => _data = new List<WebHookReceived>(); | |||
public InMemoryHooksRepository() => _data = new List<WebHookReceived>(); | |||
public Task AddNew(WebHookReceived hook) | |||
{ | |||
_data.Add(hook); | |||
return Task.CompletedTask; | |||
} | |||
public Task AddNew(WebHookReceived hook) | |||
{ | |||
_data.Add(hook); | |||
return Task.CompletedTask; | |||
} | |||
public Task<IEnumerable<WebHookReceived>> GetAll() | |||
{ | |||
return Task.FromResult(_data.AsEnumerable()); | |||
} | |||
public Task<IEnumerable<WebHookReceived>> GetAll() | |||
{ | |||
return Task.FromResult(_data.AsEnumerable()); | |||
} | |||
} |
@ -1,32 +1,24 @@ | |||
using Microsoft.Extensions.Options; | |||
using System.Collections.Generic; | |||
using System.Net.Http; | |||
using System.Threading.Tasks; | |||
using WebhookClient.Models; | |||
using System.Text.Json; | |||
namespace WebhookClient.Services; | |||
namespace WebhookClient.Services | |||
public class WebhooksClient : IWebhooksClient | |||
{ | |||
public class WebhooksClient : IWebhooksClient | |||
{ | |||
private readonly IHttpClientFactory _httpClientFactory; | |||
private readonly Settings _settings; | |||
public WebhooksClient(IHttpClientFactory httpClientFactory, IOptions<Settings> settings) | |||
{ | |||
_httpClientFactory = httpClientFactory; | |||
_settings = settings.Value; | |||
} | |||
public async Task<IEnumerable<WebhookResponse>> LoadWebhooks() | |||
private readonly IHttpClientFactory _httpClientFactory; | |||
private readonly Settings _settings; | |||
public WebhooksClient(IHttpClientFactory httpClientFactory, IOptions<Settings> settings) | |||
{ | |||
_httpClientFactory = httpClientFactory; | |||
_settings = settings.Value; | |||
} | |||
public async Task<IEnumerable<WebhookResponse>> LoadWebhooks() | |||
{ | |||
var client = _httpClientFactory.CreateClient("GrantClient"); | |||
var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks"); | |||
var json = await response.Content.ReadAsStringAsync(); | |||
var subscriptions = JsonSerializer.Deserialize<IEnumerable<WebhookResponse>>(json, new JsonSerializerOptions | |||
{ | |||
var client = _httpClientFactory.CreateClient("GrantClient"); | |||
var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks"); | |||
var json = await response.Content.ReadAsStringAsync(); | |||
var subscriptions = JsonSerializer.Deserialize<IEnumerable<WebhookResponse>>(json, new JsonSerializerOptions | |||
{ | |||
PropertyNameCaseInsensitive = true | |||
}); | |||
return subscriptions; | |||
} | |||
PropertyNameCaseInsensitive = true | |||
}); | |||
return subscriptions; | |||
} | |||
} |
@ -1,14 +1,13 @@ | |||
namespace WebhookClient | |||
namespace WebhookClient; | |||
public class Settings | |||
{ | |||
public class Settings | |||
{ | |||
public string Token { get; set; } | |||
public string IdentityUrl { get; set; } | |||
public string CallBackUrl { get; set; } | |||
public string WebhooksUrl { get; set; } | |||
public string SelfUrl { get; set; } | |||
public string Token { get; set; } | |||
public string IdentityUrl { get; set; } | |||
public string CallBackUrl { get; set; } | |||
public string WebhooksUrl { get; set; } | |||
public string SelfUrl { get; set; } | |||
public bool ValidateToken { get; set; } | |||
public bool ValidateToken { get; set; } | |||
} | |||
} |
@ -1,165 +1,149 @@ | |||
using Microsoft.AspNetCore.Authentication.Cookies; | |||
using Microsoft.AspNetCore.Authentication.OpenIdConnect; | |||
using Microsoft.AspNetCore.Builder; | |||
using Microsoft.AspNetCore.Hosting; | |||
using Microsoft.AspNetCore.Http; | |||
using Microsoft.AspNetCore.Mvc; | |||
using Microsoft.Extensions.Configuration; | |||
using Microsoft.Extensions.DependencyInjection; | |||
using Microsoft.Extensions.Hosting; | |||
using System; | |||
using System.Linq; | |||
using System.Net; | |||
using System.Threading; | |||
using WebhookClient.Services; | |||
namespace WebhookClient | |||
namespace WebhookClient; | |||
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. | |||
public void ConfigureServices(IServiceCollection services) | |||
// This method gets called by the runtime. Use this method to add services to the container. | |||
public void ConfigureServices(IServiceCollection services) | |||
{ | |||
services.AddSession(opt => | |||
{ | |||
opt.Cookie.Name = ".eShopWebhooks.Session"; | |||
}) | |||
.AddConfiguration(Configuration) | |||
.AddHttpClientServices(Configuration) | |||
.AddCustomAuthentication(Configuration) | |||
.AddTransient<IWebhooksClient, WebhooksClient>() | |||
.AddSingleton<IHooksRepository, InMemoryHooksRepository>() | |||
.AddMvc() | |||
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0); | |||
services.AddControllers(); | |||
} | |||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |||
{ | |||
var pathBase = Configuration["PATH_BASE"]; | |||
if (!string.IsNullOrEmpty(pathBase)) | |||
{ | |||
services.AddSession(opt => | |||
{ | |||
opt.Cookie.Name = ".eShopWebhooks.Session"; | |||
}) | |||
.AddConfiguration(Configuration) | |||
.AddHttpClientServices(Configuration) | |||
.AddCustomAuthentication(Configuration) | |||
.AddTransient<IWebhooksClient, WebhooksClient>() | |||
.AddSingleton<IHooksRepository, InMemoryHooksRepository>() | |||
.AddMvc() | |||
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0); | |||
services.AddControllers(); | |||
app.UsePathBase(pathBase); | |||
} | |||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |||
if (env.IsDevelopment()) | |||
{ | |||
var pathBase = Configuration["PATH_BASE"]; | |||
if (!string.IsNullOrEmpty(pathBase)) | |||
{ | |||
app.UsePathBase(pathBase); | |||
} | |||
if (env.IsDevelopment()) | |||
{ | |||
app.UseDeveloperExceptionPage(); | |||
} | |||
else | |||
{ | |||
app.UseExceptionHandler("/Error"); | |||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |||
} | |||
app.Map("/check", capp => | |||
app.UseDeveloperExceptionPage(); | |||
} | |||
else | |||
{ | |||
app.UseExceptionHandler("/Error"); | |||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |||
} | |||
app.Map("/check", capp => | |||
{ | |||
capp.Run(async (context) => | |||
{ | |||
capp.Run(async (context) => | |||
if ("OPTIONS".Equals(context.Request.Method, StringComparison.InvariantCultureIgnoreCase)) | |||
{ | |||
if ("OPTIONS".Equals(context.Request.Method, StringComparison.InvariantCultureIgnoreCase)) | |||
var validateToken = bool.TrueString.Equals(Configuration["ValidateToken"], StringComparison.InvariantCultureIgnoreCase); | |||
var header = context.Request.Headers[HeaderNames.WebHookCheckHeader]; | |||
var value = header.FirstOrDefault(); | |||
var tokenToValidate = Configuration["Token"]; | |||
if (!validateToken || value == tokenToValidate) | |||
{ | |||
var validateToken = bool.TrueString.Equals(Configuration["ValidateToken"], StringComparison.InvariantCultureIgnoreCase); | |||
var header = context.Request.Headers[HeaderNames.WebHookCheckHeader]; | |||
var value = header.FirstOrDefault(); | |||
var tokenToValidate = Configuration["Token"]; | |||
if (!validateToken || value == tokenToValidate) | |||
{ | |||
if (!string.IsNullOrWhiteSpace(tokenToValidate)) | |||
{ | |||
context.Response.Headers.Add(HeaderNames.WebHookCheckHeader, tokenToValidate); | |||
} | |||
context.Response.StatusCode = (int)HttpStatusCode.OK; | |||
} | |||
else | |||
if (!string.IsNullOrWhiteSpace(tokenToValidate)) | |||
{ | |||
await context.Response.WriteAsync("Invalid token"); | |||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |||
context.Response.Headers.Add(HeaderNames.WebHookCheckHeader, tokenToValidate); | |||
} | |||
context.Response.StatusCode = (int)HttpStatusCode.OK; | |||
} | |||
else | |||
{ | |||
await context.Response.WriteAsync("Invalid token"); | |||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |||
} | |||
}); | |||
}); | |||
// Fix samesite issue when running eShop from docker-compose locally as by default http protocol is being used | |||
// Refer to https://github.com/dotnet-architecture/eShopOnContainers/issues/1391 | |||
app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Lax }); | |||
app.UseStaticFiles(); | |||
app.UseSession(); | |||
app.UseRouting(); | |||
app.UseAuthentication(); | |||
app.UseAuthorization(); | |||
app.UseEndpoints(endpoints => | |||
{ | |||
endpoints.MapDefaultControllerRoute(); | |||
endpoints.MapRazorPages(); | |||
} | |||
else | |||
{ | |||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest; | |||
} | |||
}); | |||
} | |||
}); | |||
// Fix samesite issue when running eShop from docker-compose locally as by default http protocol is being used | |||
// Refer to https://github.com/dotnet-architecture/eShopOnContainers/issues/1391 | |||
app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Lax }); | |||
app.UseStaticFiles(); | |||
app.UseSession(); | |||
app.UseRouting(); | |||
app.UseAuthentication(); | |||
app.UseAuthorization(); | |||
app.UseEndpoints(endpoints => | |||
{ | |||
endpoints.MapDefaultControllerRoute(); | |||
endpoints.MapRazorPages(); | |||
}); | |||
} | |||
} | |||
static class ServiceExtensions | |||
static class ServiceExtensions | |||
{ | |||
public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration configuration) | |||
{ | |||
public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration configuration) | |||
{ | |||
services.AddOptions(); | |||
services.Configure<Settings>(configuration); | |||
return services; | |||
} | |||
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration) | |||
{ | |||
var identityUrl = configuration.GetValue<string>("IdentityUrl"); | |||
var callBackUrl = configuration.GetValue<string>("CallBackUrl"); | |||
// Add Authentication services | |||
services.AddAuthentication(options => | |||
{ | |||
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |||
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; | |||
}) | |||
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromHours(2)) | |||
.AddOpenIdConnect(options => | |||
{ | |||
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |||
options.Authority = identityUrl.ToString(); | |||
options.SignedOutRedirectUri = callBackUrl.ToString(); | |||
options.ClientId = "webhooksclient"; | |||
options.ClientSecret = "secret"; | |||
options.ResponseType = "code id_token"; | |||
options.SaveTokens = true; | |||
options.GetClaimsFromUserInfoEndpoint = true; | |||
options.RequireHttpsMetadata = false; | |||
options.Scope.Add("openid"); | |||
options.Scope.Add("webhooks"); | |||
}); | |||
services.AddOptions(); | |||
services.Configure<Settings>(configuration); | |||
return services; | |||
} | |||
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration) | |||
{ | |||
var identityUrl = configuration.GetValue<string>("IdentityUrl"); | |||
var callBackUrl = configuration.GetValue<string>("CallBackUrl"); | |||
return services; | |||
} | |||
// Add Authentication services | |||
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration) | |||
services.AddAuthentication(options => | |||
{ | |||
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |||
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; | |||
}) | |||
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromHours(2)) | |||
.AddOpenIdConnect(options => | |||
{ | |||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); | |||
services.AddTransient<HttpClientAuthorizationDelegatingHandler>(); | |||
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(Timeout.InfiniteTimeSpan); | |||
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |||
options.Authority = identityUrl.ToString(); | |||
options.SignedOutRedirectUri = callBackUrl.ToString(); | |||
options.ClientId = "webhooksclient"; | |||
options.ClientSecret = "secret"; | |||
options.ResponseType = "code id_token"; | |||
options.SaveTokens = true; | |||
options.GetClaimsFromUserInfoEndpoint = true; | |||
options.RequireHttpsMetadata = false; | |||
options.Scope.Add("openid"); | |||
options.Scope.Add("webhooks"); | |||
}); | |||
return services; | |||
} | |||
//add http client services | |||
services.AddHttpClient("GrantClient") | |||
.SetHandlerLifetime(TimeSpan.FromMinutes(5)) | |||
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>(); | |||
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration) | |||
{ | |||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); | |||
services.AddTransient<HttpClientAuthorizationDelegatingHandler>(); | |||
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(Timeout.InfiniteTimeSpan); | |||
return services; | |||
} | |||
//add http client services | |||
services.AddHttpClient("GrantClient") | |||
.SetHandlerLifetime(TimeSpan.FromMinutes(5)) | |||
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>(); | |||
return services; | |||
} | |||
} |