Included file scope namespaces for Webhookclient
This commit is contained in:
parent
ce025e5387
commit
31359d4c40
@ -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");
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
var user = User as ClaimsPrincipal;
|
||||
|
||||
var token = await HttpContext.GetTokenAsync("access_token");
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
ViewData["access_token"] = token;
|
||||
}
|
||||
|
||||
return RedirectToPage("/Index");
|
||||
ViewData["access_token"] = token;
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
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;
|
||||
|
||||
public WebhooksReceivedController(IOptions<Settings> settings, ILogger<WebhooksReceivedController> logger, IHooksRepository hooksRepository)
|
||||
{
|
||||
_settings = settings.Value;
|
||||
_logger = logger;
|
||||
_hooksRepository = hooksRepository;
|
||||
}
|
||||
|
||||
private readonly Settings _settings;
|
||||
private readonly ILogger _logger;
|
||||
private readonly IHooksRepository _hooksRepository;
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> NewWebhook(WebhookData hook)
|
||||
{
|
||||
var header = Request.Headers[HeaderNames.WebHookCheckHeader];
|
||||
var token = header.FirstOrDefault();
|
||||
|
||||
public WebhooksReceivedController(IOptions<Settings> settings, ILogger<WebhooksReceivedController> logger, IHooksRepository hooksRepository)
|
||||
_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)
|
||||
{
|
||||
_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();
|
||||
|
||||
_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)
|
||||
_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();
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var authorizationHeader = _httpContextAccessor.HttpContext
|
||||
.Request.Headers["Authorization"];
|
||||
|
||||
if (!string.IsNullOrEmpty(authorizationHeader))
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
var token = await GetToken();
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
var authorizationHeader = _httpContextAccessor.HttpContext
|
||||
.Request.Headers["Authorization"];
|
||||
|
||||
if (!string.IsNullOrEmpty(authorizationHeader))
|
||||
{
|
||||
request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
|
||||
}
|
||||
|
||||
var token = await GetToken();
|
||||
|
||||
if (token != null)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
}
|
||||
|
||||
return await base.SendAsync(request, cancellationToken);
|
||||
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,8 +1,4 @@
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using WebhookClient;
|
||||
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
|
||||
|
||||
IWebHostBuilder CreateWebHostBuilder(string[] args) =>
|
||||
|
@ -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;
|
||||
|
||||
public InMemoryHooksRepository() => _data = new List<WebHookReceived>();
|
||||
|
||||
public Task AddNew(WebHookReceived hook)
|
||||
{
|
||||
private readonly List<WebHookReceived> _data;
|
||||
_data.Add(hook);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public InMemoryHooksRepository() => _data = new List<WebHookReceived>();
|
||||
|
||||
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)
|
||||
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
|
||||
{
|
||||
_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
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
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.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))
|
||||
{
|
||||
Configuration = configuration;
|
||||
app.UsePathBase(pathBase);
|
||||
}
|
||||
|
||||
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)
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
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.UseDeveloperExceptionPage();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
else
|
||||
{
|
||||
|
||||
var pathBase = Configuration["PATH_BASE"];
|
||||
if (!string.IsNullOrEmpty(pathBase))
|
||||
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) =>
|
||||
{
|
||||
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 =>
|
||||
{
|
||||
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))
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(tokenToValidate))
|
||||
{
|
||||
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;
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
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 });
|
||||
// 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
|
||||
{
|
||||
public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration configuration)
|
||||
app.UseStaticFiles();
|
||||
app.UseSession();
|
||||
app.UseRouting();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
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");
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
|
||||
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(Timeout.InfiniteTimeSpan);
|
||||
|
||||
//add http client services
|
||||
services.AddHttpClient("GrantClient")
|
||||
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
|
||||
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
endpoints.MapDefaultControllerRoute();
|
||||
endpoints.MapRazorPages();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static class ServiceExtensions
|
||||
{
|
||||
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");
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
|
||||
services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(Timeout.InfiniteTimeSpan);
|
||||
|
||||
//add http client services
|
||||
services.AddHttpClient("GrantClient")
|
||||
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
|
||||
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user