diff --git a/.gitignore b/.gitignore index be040b4..17be988 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,418 @@ -bin/ -obj/ -out/ +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio,visualstudiocode + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode diff --git a/Services/DiscoveryDocument.cs b/Services/DiscoveryDocument.cs deleted file mode 100644 index 1fdfae3..0000000 --- a/Services/DiscoveryDocument.cs +++ /dev/null @@ -1,3 +0,0 @@ -public class DiscoveryDocument { - public string token_endpoint { get; set;} = ""; -} diff --git a/Middleware/GatewayEndpoints.cs b/src/YarpAuthProxy.BffLibrary/Middleware/GatewayEndpoints.cs similarity index 95% rename from Middleware/GatewayEndpoints.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/GatewayEndpoints.cs index 70f07a3..39b96e9 100644 --- a/Middleware/GatewayEndpoints.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/GatewayEndpoints.cs @@ -2,6 +2,10 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +namespace YarpAuthProxy.BffLibrary.Middleware; public static class GatewayEndpoints { diff --git a/Middleware/GatewayPipeline.cs b/src/YarpAuthProxy.BffLibrary/Middleware/GatewayPipeline.cs similarity index 69% rename from Middleware/GatewayPipeline.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/GatewayPipeline.cs index 9cd5156..b152c36 100644 --- a/Middleware/GatewayPipeline.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/GatewayPipeline.cs @@ -1,3 +1,9 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using YarpAuthProxy.BffLibrary.Services; + +namespace YarpAuthProxy.BffLibrary.Middleware; + public static class GatewayPipeline { public static void UseGatewayPipeline(this IReverseProxyApplicationBuilder pipeline) diff --git a/Middleware/GatewaySetup.cs b/src/YarpAuthProxy.BffLibrary/Middleware/GatewaySetup.cs similarity index 85% rename from Middleware/GatewaySetup.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/GatewaySetup.cs index be4d8a5..ce40707 100644 --- a/Middleware/GatewaySetup.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/GatewaySetup.cs @@ -1,10 +1,18 @@ using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using YarpAuthProxy.BffLibrary.Services; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Middleware; public static class GatewaySetup { - private static readonly string ENV_GATEWAY_CONFIG = "GATEWAY_CONFIG"; + private static readonly string ENV_GATEWAY_CONFIG = "GATEWAY_CONFIG"; public static void AddConfigFiles(this WebApplicationBuilder builder) { @@ -21,28 +29,31 @@ public static void AddConfigFiles(this WebApplicationBuilder builder) } } - private static void AddTokenExchangeService(this WebApplicationBuilder builder, GatewayConfig config) { + private static void AddTokenExchangeService(this WebApplicationBuilder builder, GatewayConfig config) + { var strategy = config.TokenExchangeStrategy; - if (string.IsNullOrEmpty(strategy)) { + if (string.IsNullOrEmpty(strategy)) + { strategy = "none"; } - switch(strategy.ToLower()) { + switch (strategy.ToLower()) + { case "none": - builder.Services.AddSingleton(); - break; + builder.Services.AddSingleton(); + break; case "azuread": - builder.Services.AddSingleton(); - break; + builder.Services.AddSingleton(); + break; case "default": - builder.Services.AddSingleton(); - break; + builder.Services.AddSingleton(); + break; default: throw new ArgumentException($"Unsupported TokenExchangeStrategy in config found: {config.TokenExchangeStrategy}. Possible values: none, AzureAd, default"); - + } } @@ -53,7 +64,7 @@ public static void AddGateway(this WebApplicationBuilder builder, GatewayConfig builder.Services.AddSingleton(disco); builder.Services.AddSingleton(config); - + builder.Services.AddSingleton(); builder.AddTokenExchangeService(config); diff --git a/Middleware/LogoutHandler.cs b/src/YarpAuthProxy.BffLibrary/Middleware/LogoutHandler.cs similarity index 84% rename from Middleware/LogoutHandler.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/LogoutHandler.cs index 8dc171f..53b36b4 100644 --- a/Middleware/LogoutHandler.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/LogoutHandler.cs @@ -1,6 +1,10 @@ using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using YarpAuthProxy.BffLibrary.Utils.Config; -public static class LogoutHandler { +namespace YarpAuthProxy.BffLibrary.Middleware; + +public static class LogoutHandler +{ public static void HandleLogout(RedirectContext context, GatewayConfig config) { if (!string.IsNullOrEmpty(config.LogoutUrl)) diff --git a/Middleware/SessionKeys.cs b/src/YarpAuthProxy.BffLibrary/Middleware/SessionKeys.cs similarity index 78% rename from Middleware/SessionKeys.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/SessionKeys.cs index 4df7a1e..5dae917 100644 --- a/Middleware/SessionKeys.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/SessionKeys.cs @@ -1,4 +1,7 @@ -public class SessionKeys { +namespace YarpAuthProxy.BffLibrary.Middleware; + +public class SessionKeys +{ public const string ACCESS_TOKEN = "accessToken"; public const string ID_TOKEN = "idToken"; public const string REFRESH_TOKEN = "refreshToken"; diff --git a/Middleware/TokenHandler.cs b/src/YarpAuthProxy.BffLibrary/Middleware/TokenHandler.cs similarity index 87% rename from Middleware/TokenHandler.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/TokenHandler.cs index c9ee78c..abd393d 100644 --- a/Middleware/TokenHandler.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/TokenHandler.cs @@ -1,10 +1,16 @@ using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; -public class TokenHandler { +namespace YarpAuthProxy.BffLibrary.Middleware; + +public class TokenHandler +{ private ILogger logger; - public TokenHandler(ILogger logger) { + public TokenHandler(ILogger logger) + { this.logger = logger; } diff --git a/Middleware/XsrfMiddleware.cs b/src/YarpAuthProxy.BffLibrary/Middleware/XsrfMiddleware.cs similarity index 86% rename from Middleware/XsrfMiddleware.cs rename to src/YarpAuthProxy.BffLibrary/Middleware/XsrfMiddleware.cs index 3576d11..6207b3b 100644 --- a/Middleware/XsrfMiddleware.cs +++ b/src/YarpAuthProxy.BffLibrary/Middleware/XsrfMiddleware.cs @@ -1,8 +1,15 @@ using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Middleware; public static class XsrfMiddleware { - public static void UseXsrfCookie(this WebApplication app) { + public static void UseXsrfCookie(this WebApplication app) + { app.UseXsrfCookieCreator(); app.UseXsrfCookieChecks(); } diff --git a/Services/ApiTokenService.cs b/src/YarpAuthProxy.BffLibrary/Services/ApiTokenService.cs similarity index 77% rename from Services/ApiTokenService.cs rename to src/YarpAuthProxy.BffLibrary/Services/ApiTokenService.cs index efca5f4..031b72c 100644 --- a/Services/ApiTokenService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/ApiTokenService.cs @@ -1,4 +1,12 @@ -public class ApiTokenService { +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using YarpAuthProxy.BffLibrary.Middleware; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + +public class ApiTokenService +{ private ITokenExchangeService tokenExchangeService; private ILogger logger; @@ -6,7 +14,8 @@ public class ApiTokenService { public ApiTokenService( ITokenExchangeService tokenExchangeService, ILogger logger - ) { + ) + { this.tokenExchangeService = tokenExchangeService; this.logger = logger; } @@ -16,22 +25,27 @@ public void InvalidateApiTokens(HttpContext ctx) ctx.Session.Remove(SessionKeys.API_ACCESS_TOKEN); } - private TokenExchangeResponse? GetCachedApiToken(HttpContext ctx, ApiConfig apiConfig) { + private TokenExchangeResponse? GetCachedApiToken(HttpContext ctx, ApiConfig apiConfig) + { var cache = ctx.Session.GetObject>(SessionKeys.API_ACCESS_TOKEN); - if (cache == null) { + if (cache == null) + { return null; } - if (!cache.ContainsKey(apiConfig.ApiPath)) { + if (!cache.ContainsKey(apiConfig.ApiPath)) + { return null; } return cache[apiConfig.ApiPath]; } - private void SetCachedApiToken(HttpContext ctx, ApiConfig apiConfig, TokenExchangeResponse response) { + private void SetCachedApiToken(HttpContext ctx, ApiConfig apiConfig, TokenExchangeResponse response) + { var cache = ctx.Session.GetObject>(SessionKeys.API_ACCESS_TOKEN); - if (cache == null) { + if (cache == null) + { cache = new Dictionary(); } @@ -44,7 +58,8 @@ public async Task LookupApiToken(HttpContext ctx, ApiConfig apiConfig, s { var apiToken = GetCachedApiToken(ctx, apiConfig); - if (apiToken != null) { + if (apiToken != null) + { // TODO: Perform individual token refresh return apiToken.access_token; } diff --git a/Services/AzureAdTokenExchangeService.cs b/src/YarpAuthProxy.BffLibrary/Services/AzureAdTokenExchangeService.cs similarity index 92% rename from Services/AzureAdTokenExchangeService.cs rename to src/YarpAuthProxy.BffLibrary/Services/AzureAdTokenExchangeService.cs index 69af17b..763c57c 100644 --- a/Services/AzureAdTokenExchangeService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/AzureAdTokenExchangeService.cs @@ -1,4 +1,7 @@ +using System.Net.Http.Json; +using YarpAuthProxy.BffLibrary.Utils.Config; +namespace YarpAuthProxy.BffLibrary.Services; public class AzureAdTokenExchangeService : ITokenExchangeService { diff --git a/src/YarpAuthProxy.BffLibrary/Services/DiscoveryDocument.cs b/src/YarpAuthProxy.BffLibrary/Services/DiscoveryDocument.cs new file mode 100644 index 0000000..cf80178 --- /dev/null +++ b/src/YarpAuthProxy.BffLibrary/Services/DiscoveryDocument.cs @@ -0,0 +1,6 @@ +namespace YarpAuthProxy.BffLibrary.Services; + +public class DiscoveryDocument +{ + public string token_endpoint { get; set; } = ""; +} diff --git a/Services/DiscoveryService.cs b/src/YarpAuthProxy.BffLibrary/Services/DiscoveryService.cs similarity index 65% rename from Services/DiscoveryService.cs rename to src/YarpAuthProxy.BffLibrary/Services/DiscoveryService.cs index b23166a..6c982b7 100644 --- a/Services/DiscoveryService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/DiscoveryService.cs @@ -1,15 +1,22 @@ -public class DiscoveryService { +using System.Net.Http.Json; + +namespace YarpAuthProxy.BffLibrary.Services; + +public class DiscoveryService +{ private readonly string DISCO_URL = ".well-known/openid-configuration"; - public async Task loadDiscoveryDocument(string authority) { - var httpClient = new HttpClient(); + public async Task loadDiscoveryDocument(string authority) + { + var httpClient = new HttpClient(); var url = UrlUtils.CombineUrls(authority, DISCO_URL); var doc = await httpClient.GetFromJsonAsync(url); - - if (doc == null) { + + if (doc == null) + { throw new Exception("error loading discovery document from " + url); } diff --git a/Services/GatewayService.cs b/src/YarpAuthProxy.BffLibrary/Services/GatewayService.cs similarity index 92% rename from Services/GatewayService.cs rename to src/YarpAuthProxy.BffLibrary/Services/GatewayService.cs index 7a39a06..37285a1 100644 --- a/Services/GatewayService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/GatewayService.cs @@ -1,3 +1,10 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using YarpAuthProxy.BffLibrary.Middleware; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + public class GatewayService { private TokenRefreshService tokenRefreshService; @@ -10,8 +17,9 @@ public GatewayService( GatewayConfig config, ApiTokenService apiTokenService, ILogger logger - ) { - this.tokenRefreshService = tokenRefreshService; + ) + { + this.tokenRefreshService = tokenRefreshService; this.config = config; this.apiTokenService = apiTokenService; this.logger = logger; @@ -98,9 +106,9 @@ public async Task AddToken(HttpContext ctx) if (!string.IsNullOrEmpty(token) && apiConfig != null) { var apiToken = await GetApiToken(ctx, apiTokenService, token, apiConfig); - + logger.LogDebug($"---- Adding Token for reqeuest ----\n{currentUrl}\n\n{apiToken}\n--------"); - + ctx.Request.Headers.Add("Authorization", "Bearer " + apiToken); } } diff --git a/Services/ITokenExchangeService.cs b/src/YarpAuthProxy.BffLibrary/Services/ITokenExchangeService.cs similarity index 57% rename from Services/ITokenExchangeService.cs rename to src/YarpAuthProxy.BffLibrary/Services/ITokenExchangeService.cs index b76413d..536eb68 100644 --- a/Services/ITokenExchangeService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/ITokenExchangeService.cs @@ -1,3 +1,7 @@ +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + public interface ITokenExchangeService { Task Exchange(string accessToken, ApiConfig apiConfig); diff --git a/Services/NullTokenExchangeService.cs b/src/YarpAuthProxy.BffLibrary/Services/NullTokenExchangeService.cs similarity index 67% rename from Services/NullTokenExchangeService.cs rename to src/YarpAuthProxy.BffLibrary/Services/NullTokenExchangeService.cs index edddf97..8bac812 100644 --- a/Services/NullTokenExchangeService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/NullTokenExchangeService.cs @@ -1,8 +1,13 @@ +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + public class NullTokenExchangeService : ITokenExchangeService { public Task Exchange(string accessToken, ApiConfig apiConfig) { - var result = new TokenExchangeResponse { + var result = new TokenExchangeResponse + { access_token = "", expires_in = 0, refresh_token = "", diff --git a/Services/RefreshResponse.cs b/src/YarpAuthProxy.BffLibrary/Services/RefreshResponse.cs similarity index 71% rename from Services/RefreshResponse.cs rename to src/YarpAuthProxy.BffLibrary/Services/RefreshResponse.cs index d842876..75b515f 100644 --- a/Services/RefreshResponse.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/RefreshResponse.cs @@ -1,4 +1,7 @@ -public class RefreshResponse { +namespace YarpAuthProxy.BffLibrary.Services; + +public class RefreshResponse +{ public string access_token { get; set; } = ""; public string id_token { get; set; } = ""; public string refresh_token { get; set; } = ""; diff --git a/Services/TokenEchangeResponse.cs b/src/YarpAuthProxy.BffLibrary/Services/TokenEchangeResponse.cs similarity index 63% rename from Services/TokenEchangeResponse.cs rename to src/YarpAuthProxy.BffLibrary/Services/TokenEchangeResponse.cs index 5ab7ea6..3445dfa 100644 --- a/Services/TokenEchangeResponse.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/TokenEchangeResponse.cs @@ -1,4 +1,7 @@ -public class TokenExchangeResponse { +namespace YarpAuthProxy.BffLibrary.Services; + +public class TokenExchangeResponse +{ public string access_token { get; set; } = ""; public string refresh_token { get; set; } = ""; public long expires_in { get; set; } diff --git a/Services/TokenExchangeService.cs b/src/YarpAuthProxy.BffLibrary/Services/TokenExchangeService.cs similarity index 92% rename from Services/TokenExchangeService.cs rename to src/YarpAuthProxy.BffLibrary/Services/TokenExchangeService.cs index 8d28cf4..07d5952 100644 --- a/Services/TokenExchangeService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/TokenExchangeService.cs @@ -1,3 +1,8 @@ +using System.Net.Http.Json; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + public class TokenExchangeService : ITokenExchangeService { private DiscoveryDocument disco; diff --git a/Services/TokenRefreshService.cs b/src/YarpAuthProxy.BffLibrary/Services/TokenRefreshService.cs similarity index 76% rename from Services/TokenRefreshService.cs rename to src/YarpAuthProxy.BffLibrary/Services/TokenRefreshService.cs index fbc1a0c..5aefebc 100644 --- a/Services/TokenRefreshService.cs +++ b/src/YarpAuthProxy.BffLibrary/Services/TokenRefreshService.cs @@ -1,14 +1,22 @@ -public class TokenRefreshService { +using System.Net.Http.Json; +using YarpAuthProxy.BffLibrary.Utils.Config; + +namespace YarpAuthProxy.BffLibrary.Services; + +public class TokenRefreshService +{ private DiscoveryDocument disco; private GatewayConfig config; - - public TokenRefreshService(GatewayConfig config, DiscoveryDocument disco) { + + public TokenRefreshService(GatewayConfig config, DiscoveryDocument disco) + { this.disco = disco; this.config = config; } - public async Task RefreshAsync(string refreshToken) { + public async Task RefreshAsync(string refreshToken) + { var payload = new Dictionary(); payload.Add("grant_type", "refresh_token"); payload.Add("refresh_token", refreshToken); @@ -16,8 +24,9 @@ public TokenRefreshService(GatewayConfig config, DiscoveryDocument disco) { payload.Add("client_secret", config.ClientSecret); var httpClient = new HttpClient(); - - var request = new HttpRequestMessage { + + var request = new HttpRequestMessage + { RequestUri = new Uri(disco.token_endpoint), Method = HttpMethod.Post, Content = new FormUrlEncodedContent(payload) @@ -25,7 +34,8 @@ public TokenRefreshService(GatewayConfig config, DiscoveryDocument disco) { var response = await httpClient.SendAsync(request); - if (!response.IsSuccessStatusCode) { + if (!response.IsSuccessStatusCode) + { return null; } @@ -35,4 +45,3 @@ public TokenRefreshService(GatewayConfig config, DiscoveryDocument disco) { } } - \ No newline at end of file diff --git a/Utils/Config/ApiConfig.cs b/src/YarpAuthProxy.BffLibrary/Utils/Config/ApiConfig.cs similarity index 65% rename from Utils/Config/ApiConfig.cs rename to src/YarpAuthProxy.BffLibrary/Utils/Config/ApiConfig.cs index 4fbf78d..6903142 100644 --- a/Utils/Config/ApiConfig.cs +++ b/src/YarpAuthProxy.BffLibrary/Utils/Config/ApiConfig.cs @@ -1,4 +1,6 @@ -public record ApiConfig { +namespace YarpAuthProxy.BffLibrary.Utils.Config; +public record ApiConfig +{ public string ApiPath { get; set; } = ""; public string ApiScopes { get; set; } = ""; public string ApiAudience { get; set; } = ""; diff --git a/Utils/Config/GatewayConfig.cs b/src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfig.cs similarity index 78% rename from Utils/Config/GatewayConfig.cs rename to src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfig.cs index 6855631..c8014f6 100644 --- a/Utils/Config/GatewayConfig.cs +++ b/src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfig.cs @@ -1,4 +1,6 @@ -public record GatewayConfig { +namespace YarpAuthProxy.BffLibrary.Utils.Config; +public record GatewayConfig +{ public string Url { get; set; } = ""; public int SessionTimeoutInMin { get; set; } public string TokenExchangeStrategy { get; set; } = ""; @@ -9,5 +11,5 @@ public record GatewayConfig { public string LogoutUrl { get; set; } = ""; public bool QueryUserInfoEndpoint { get; set; } = true; // public string ApiScopes { get; set; } = ""; - public ApiConfig[] ApiConfigs { get; set; } = {}; + public ApiConfig[] ApiConfigs { get; set; } = { }; } diff --git a/Utils/Config/GatewayConfigReader.cs b/src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfigReader.cs similarity index 91% rename from Utils/Config/GatewayConfigReader.cs rename to src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfigReader.cs index d2b2d0d..f3fceed 100644 --- a/Utils/Config/GatewayConfigReader.cs +++ b/src/YarpAuthProxy.BffLibrary/Utils/Config/GatewayConfigReader.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.Configuration; + +namespace YarpAuthProxy.BffLibrary.Utils.Config; + public static class GetewayConfigReader { public static GatewayConfig GetGatewayConfig(this ConfigurationManager config) @@ -7,7 +11,7 @@ public static GatewayConfig GetGatewayConfig(this ConfigurationManager config) Url = config.GetValue("Gateway:Url", ""), SessionTimeoutInMin = config.GetValue("Gateway:SessionTimeoutInMin", 60), TokenExchangeStrategy = config.GetValue("Gateway:TokenExchangeStrategy", ""), - + Authority = config.GetValue("OpenIdConnect:Authority"), ClientId = config.GetValue("OpenIdConnect:ClientId"), ClientSecret = config.GetValue("OpenIdConnect:ClientSecret"), diff --git a/Utils/SessionUtils.cs b/src/YarpAuthProxy.BffLibrary/Utils/SessionUtils.cs similarity index 51% rename from Utils/SessionUtils.cs rename to src/YarpAuthProxy.BffLibrary/Utils/SessionUtils.cs index 7e23a44..25a1eae 100644 --- a/Utils/SessionUtils.cs +++ b/src/YarpAuthProxy.BffLibrary/Utils/SessionUtils.cs @@ -1,21 +1,29 @@ +using Microsoft.AspNetCore.Http; using System.Text.Json; -public static class SessionUtils { +namespace YarpAuthProxy.BffLibrary; - public static void SetObject(this Microsoft.AspNetCore.Http.ISession session, string key, T value) { +public static class SessionUtils +{ + + public static void SetObject(this Microsoft.AspNetCore.Http.ISession session, string key, T value) + { var json = JsonSerializer.Serialize(value); session.SetString(key, json); } - public static T? GetObject(this Microsoft.AspNetCore.Http.ISession session, string key) { - if (!session.Keys.Contains(key)) { - return default(T); + public static T? GetObject(this Microsoft.AspNetCore.Http.ISession session, string key) + { + if (!session.Keys.Contains(key)) + { + return default(T); } var value = session.GetString(key); - if (string.IsNullOrEmpty(value)) { - return default(T); + if (string.IsNullOrEmpty(value)) + { + return default(T); } return JsonSerializer.Deserialize(value); diff --git a/Utils/UrlUtils.cs b/src/YarpAuthProxy.BffLibrary/Utils/UrlUtils.cs similarity index 74% rename from Utils/UrlUtils.cs rename to src/YarpAuthProxy.BffLibrary/Utils/UrlUtils.cs index 54e70ca..80a7580 100644 --- a/Utils/UrlUtils.cs +++ b/src/YarpAuthProxy.BffLibrary/Utils/UrlUtils.cs @@ -1,4 +1,6 @@ -public static class UrlUtils { +namespace YarpAuthProxy.BffLibrary; +public static class UrlUtils +{ public static string CombineUrls(string uri1, string uri2) { uri1 = uri1.TrimEnd('/'); diff --git a/auth-gateway.csproj b/src/YarpAuthProxy.BffLibrary/YarpAuthProxy.BffLibrary.csproj similarity index 76% rename from auth-gateway.csproj rename to src/YarpAuthProxy.BffLibrary/YarpAuthProxy.BffLibrary.csproj index 5409a38..592450f 100644 --- a/auth-gateway.csproj +++ b/src/YarpAuthProxy.BffLibrary/YarpAuthProxy.BffLibrary.csproj @@ -1,15 +1,15 @@ - + net6.0 - enable enable + enable - + - + diff --git a/.dockerignore b/src/YarpAuthProxy.Sample/.dockerignore similarity index 100% rename from .dockerignore rename to src/YarpAuthProxy.Sample/.dockerignore diff --git a/.vscode/launch.json b/src/YarpAuthProxy.Sample/.vscode/launch.json similarity index 100% rename from .vscode/launch.json rename to src/YarpAuthProxy.Sample/.vscode/launch.json diff --git a/.vscode/settings.json b/src/YarpAuthProxy.Sample/.vscode/settings.json similarity index 100% rename from .vscode/settings.json rename to src/YarpAuthProxy.Sample/.vscode/settings.json diff --git a/.vscode/tasks.json b/src/YarpAuthProxy.Sample/.vscode/tasks.json similarity index 100% rename from .vscode/tasks.json rename to src/YarpAuthProxy.Sample/.vscode/tasks.json diff --git a/Dockerfile b/src/YarpAuthProxy.Sample/Dockerfile similarity index 100% rename from Dockerfile rename to src/YarpAuthProxy.Sample/Dockerfile diff --git a/Program.cs b/src/YarpAuthProxy.Sample/Program.cs similarity index 85% rename from Program.cs rename to src/YarpAuthProxy.Sample/Program.cs index cd2ce70..4d6a252 100644 --- a/Program.cs +++ b/src/YarpAuthProxy.Sample/Program.cs @@ -1,5 +1,9 @@ using System.IdentityModel.Tokens.Jwt; +using YarpAuthProxy.BffLibrary.Middleware; +using YarpAuthProxy.BffLibrary.Services; +using YarpAuthProxy.BffLibrary.Utils.Config; + // Disable claim mapping to get claims 1:1 from the tokens JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); diff --git a/Properties/launchSettings.json b/src/YarpAuthProxy.Sample/Properties/launchSettings.json similarity index 100% rename from Properties/launchSettings.json rename to src/YarpAuthProxy.Sample/Properties/launchSettings.json diff --git a/src/YarpAuthProxy.Sample/YarpAuthProxy.Sample.csproj b/src/YarpAuthProxy.Sample/YarpAuthProxy.Sample.csproj new file mode 100644 index 0000000..1424a91 --- /dev/null +++ b/src/YarpAuthProxy.Sample/YarpAuthProxy.Sample.csproj @@ -0,0 +1,18 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + diff --git a/appsettings.Development.json b/src/YarpAuthProxy.Sample/appsettings.Development.json similarity index 100% rename from appsettings.Development.json rename to src/YarpAuthProxy.Sample/appsettings.Development.json diff --git a/appsettings.json b/src/YarpAuthProxy.Sample/appsettings.json similarity index 100% rename from appsettings.json rename to src/YarpAuthProxy.Sample/appsettings.json diff --git a/conf/appsettings.auth0.json b/src/YarpAuthProxy.Sample/conf/appsettings.auth0.json similarity index 100% rename from conf/appsettings.auth0.json rename to src/YarpAuthProxy.Sample/conf/appsettings.auth0.json diff --git a/conf/appsettings.azure.json b/src/YarpAuthProxy.Sample/conf/appsettings.azure.json similarity index 100% rename from conf/appsettings.azure.json rename to src/YarpAuthProxy.Sample/conf/appsettings.azure.json diff --git a/conf/appsettings.azure.simple.json b/src/YarpAuthProxy.Sample/conf/appsettings.azure.simple.json similarity index 100% rename from conf/appsettings.azure.simple.json rename to src/YarpAuthProxy.Sample/conf/appsettings.azure.simple.json diff --git a/conf/appsettings.identity-server.json b/src/YarpAuthProxy.Sample/conf/appsettings.identity-server.json similarity index 100% rename from conf/appsettings.identity-server.json rename to src/YarpAuthProxy.Sample/conf/appsettings.identity-server.json diff --git a/conf/appsettings.keycloak.json b/src/YarpAuthProxy.Sample/conf/appsettings.keycloak.json similarity index 100% rename from conf/appsettings.keycloak.json rename to src/YarpAuthProxy.Sample/conf/appsettings.keycloak.json diff --git a/conf/appsettings.keycloak.simple.json b/src/YarpAuthProxy.Sample/conf/appsettings.keycloak.simple.json similarity index 100% rename from conf/appsettings.keycloak.simple.json rename to src/YarpAuthProxy.Sample/conf/appsettings.keycloak.simple.json diff --git a/docker-compose.yml b/src/YarpAuthProxy.Sample/docker-compose.yml similarity index 100% rename from docker-compose.yml rename to src/YarpAuthProxy.Sample/docker-compose.yml diff --git a/docker.md b/src/YarpAuthProxy.Sample/docker.md similarity index 100% rename from docker.md rename to src/YarpAuthProxy.Sample/docker.md diff --git a/src/YarpAuthProxy.sln b/src/YarpAuthProxy.sln new file mode 100644 index 0000000..4a8d63b --- /dev/null +++ b/src/YarpAuthProxy.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34024.191 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "YarpAuthProxy.Sample", "YarpAuthProxy.Sample\YarpAuthProxy.Sample.csproj", "{B4E22FF2-B721-4906-985C-C3C9299773C4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YarpAuthProxy.BffLibrary", "YarpAuthProxy.BffLibrary\YarpAuthProxy.BffLibrary.csproj", "{5E9830A2-E917-4AC5-8C4A-6D92AC74ACB2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B4E22FF2-B721-4906-985C-C3C9299773C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B4E22FF2-B721-4906-985C-C3C9299773C4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B4E22FF2-B721-4906-985C-C3C9299773C4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B4E22FF2-B721-4906-985C-C3C9299773C4}.Release|Any CPU.Build.0 = Release|Any CPU + {5E9830A2-E917-4AC5-8C4A-6D92AC74ACB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E9830A2-E917-4AC5-8C4A-6D92AC74ACB2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E9830A2-E917-4AC5-8C4A-6D92AC74ACB2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E9830A2-E917-4AC5-8C4A-6D92AC74ACB2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F547E090-1228-4CE6-9A2C-2490F0E766D1} + EndGlobalSection +EndGlobal