├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── JOS.ApiKeyAuthentication.sln ├── README.md ├── src └── JOS.ApiKeyAuthentication.Web │ ├── Features │ ├── Authentication │ │ ├── ApiKey.cs │ │ ├── ApiKeyAuthenticationHandler.cs │ │ ├── ApiKeyAuthenticationOptions.cs │ │ ├── AuthenticationBuilderExtensions.cs │ │ ├── IGetApiKeyQuery.cs │ │ ├── InMemoryGetApiKeyQuery.cs │ │ └── UnauthorizedProblemDetails.cs │ ├── Authorization │ │ ├── ForbiddenProblemDetails.cs │ │ ├── OnlyEmployeesAuthorizationHandler.cs │ │ ├── OnlyEmployeesRequirement.cs │ │ ├── OnlyManagersAuthorizationHandler.cs │ │ ├── OnlyManagersRequirement.cs │ │ ├── OnlyThirdPartiesAuthorizationHandler.cs │ │ ├── OnlyThirdPartiesRequirement.cs │ │ ├── Policies.cs │ │ └── Roles.cs │ ├── Json │ │ └── DefaultJsonSerializerOptions.cs │ ├── Shared │ │ └── ApiKeyConstants.cs │ ├── Swagger │ │ └── SwaggerConfigurator.cs │ └── User │ │ └── UserController.cs │ ├── JOS.ApiKeyAuthentication.Web.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── test └── JOS.ApiKeyAuthentication.Web.Tests ├── AuthenticationIntegrationTests.cs ├── AuthorizationIntegrationTests.cs ├── JOS.ApiKeyAuthentication.Web.Tests.csproj └── Properties └── launchSettings.json /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | on: 3 | push: 4 | branches: [ develop ] 5 | pull_request: 6 | branches: [ develop ] 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Setup .NET 13 | uses: actions/setup-dotnet@v3 14 | with: 15 | dotnet-version: | 16 | 8.0.x 17 | dotnet-quality: 'ga' 18 | - name: Verify 19 | run: dotnet test -c Release --verbosity normal 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/csharp 3 | # Edit at https://www.gitignore.io/?templates=csharp 4 | 5 | ### Csharp ### 6 | ## Ignore Visual Studio temporary files, build results, and 7 | ## files generated by popular Visual Studio add-ons. 8 | ## 9 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 10 | 11 | # User-specific files 12 | *.rsuser 13 | *.suo 14 | *.user 15 | *.userosscache 16 | *.sln.docstates 17 | 18 | # User-specific files (MonoDevelop/Xamarin Studio) 19 | *.userprefs 20 | 21 | # Mono auto generated files 22 | mono_crash.* 23 | 24 | # Build results 25 | [Dd]ebug/ 26 | [Dd]ebugPublic/ 27 | [Rr]elease/ 28 | [Rr]eleases/ 29 | x64/ 30 | x86/ 31 | [Aa][Rr][Mm]/ 32 | [Aa][Rr][Mm]64/ 33 | bld/ 34 | [Bb]in/ 35 | [Oo]bj/ 36 | [Ll]og/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUNIT 51 | *.VisualState.xml 52 | TestResult.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # StyleCop 68 | StyleCopReport.xml 69 | 70 | # Files built by Visual Studio 71 | *_i.c 72 | *_p.c 73 | *_h.h 74 | *.ilk 75 | *.meta 76 | *.obj 77 | *.iobj 78 | *.pch 79 | *.pdb 80 | *.ipdb 81 | *.pgc 82 | *.pgd 83 | *.rsp 84 | *.sbr 85 | *.tlb 86 | *.tli 87 | *.tlh 88 | *.tmp 89 | *.tmp_proj 90 | *_wpftmp.csproj 91 | *.log 92 | *.vspscc 93 | *.vssscc 94 | .builds 95 | *.pidb 96 | *.svclog 97 | *.scc 98 | 99 | # Chutzpah Test files 100 | _Chutzpah* 101 | 102 | # Visual C++ cache files 103 | ipch/ 104 | *.aps 105 | *.ncb 106 | *.opendb 107 | *.opensdf 108 | *.sdf 109 | *.cachefile 110 | *.VC.db 111 | *.VC.VC.opendb 112 | 113 | # Visual Studio profiler 114 | *.psess 115 | *.vsp 116 | *.vspx 117 | *.sap 118 | 119 | # Visual Studio Trace Files 120 | *.e2e 121 | 122 | # TFS 2012 Local Workspace 123 | $tf/ 124 | 125 | # Guidance Automation Toolkit 126 | *.gpState 127 | 128 | # ReSharper is a .NET coding add-in 129 | _ReSharper*/ 130 | *.[Rr]e[Ss]harper 131 | *.DotSettings.user 132 | 133 | # JustCode is a .NET coding add-in 134 | .JustCode 135 | 136 | # TeamCity is a build add-in 137 | _TeamCity* 138 | 139 | # DotCover is a Code Coverage Tool 140 | *.dotCover 141 | 142 | # AxoCover is a Code Coverage Tool 143 | .axoCover/* 144 | !.axoCover/settings.json 145 | 146 | # Visual Studio code coverage results 147 | *.coverage 148 | *.coveragexml 149 | 150 | # NCrunch 151 | _NCrunch_* 152 | .*crunch*.local.xml 153 | nCrunchTemp_* 154 | 155 | # MightyMoose 156 | *.mm.* 157 | AutoTest.Net/ 158 | 159 | # Web workbench (sass) 160 | .sass-cache/ 161 | 162 | # Installshield output folder 163 | [Ee]xpress/ 164 | 165 | # DocProject is a documentation generator add-in 166 | DocProject/buildhelp/ 167 | DocProject/Help/*.HxT 168 | DocProject/Help/*.HxC 169 | DocProject/Help/*.hhc 170 | DocProject/Help/*.hhk 171 | DocProject/Help/*.hhp 172 | DocProject/Help/Html2 173 | DocProject/Help/html 174 | 175 | # Click-Once directory 176 | publish/ 177 | 178 | # Publish Web Output 179 | *.[Pp]ublish.xml 180 | *.azurePubxml 181 | # Note: Comment the next line if you want to checkin your web deploy settings, 182 | # but database connection strings (with potential passwords) will be unencrypted 183 | *.pubxml 184 | *.publishproj 185 | 186 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 187 | # checkin your Azure Web App publish settings, but sensitive information contained 188 | # in these scripts will be unencrypted 189 | PublishScripts/ 190 | 191 | # NuGet Packages 192 | *.nupkg 193 | # The packages folder can be ignored because of Package Restore 194 | **/[Pp]ackages/* 195 | # except build/, which is used as an MSBuild target. 196 | !**/[Pp]ackages/build/ 197 | # Uncomment if necessary however generally it will be regenerated when needed 198 | #!**/[Pp]ackages/repositories.config 199 | # NuGet v3's project.json files produces more ignorable files 200 | *.nuget.props 201 | *.nuget.targets 202 | 203 | # Microsoft Azure Build Output 204 | csx/ 205 | *.build.csdef 206 | 207 | # Microsoft Azure Emulator 208 | ecf/ 209 | rcf/ 210 | 211 | # Windows Store app package directories and files 212 | AppPackages/ 213 | BundleArtifacts/ 214 | Package.StoreAssociation.xml 215 | _pkginfo.txt 216 | *.appx 217 | *.appxbundle 218 | *.appxupload 219 | 220 | # Visual Studio cache files 221 | # files ending in .cache can be ignored 222 | *.[Cc]ache 223 | # but keep track of directories ending in .cache 224 | !?*.[Cc]ache/ 225 | 226 | # Others 227 | ClientBin/ 228 | ~$* 229 | *~ 230 | *.dbmdl 231 | *.dbproj.schemaview 232 | *.jfm 233 | *.pfx 234 | *.publishsettings 235 | orleans.codegen.cs 236 | 237 | # Including strong name files can present a security risk 238 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 239 | #*.snk 240 | 241 | # Since there are multiple workflows, uncomment next line to ignore bower_components 242 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 243 | #bower_components/ 244 | 245 | # RIA/Silverlight projects 246 | Generated_Code/ 247 | 248 | # Backup & report files from converting an old project file 249 | # to a newer Visual Studio version. Backup files are not needed, 250 | # because we have git ;-) 251 | _UpgradeReport_Files/ 252 | Backup*/ 253 | UpgradeLog*.XML 254 | UpgradeLog*.htm 255 | ServiceFabricBackup/ 256 | *.rptproj.bak 257 | 258 | # SQL Server files 259 | *.mdf 260 | *.ldf 261 | *.ndf 262 | 263 | # Business Intelligence projects 264 | *.rdl.data 265 | *.bim.layout 266 | *.bim_*.settings 267 | *.rptproj.rsuser 268 | *- Backup*.rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | 351 | # End of https://www.gitignore.io/api/csharp 352 | -------------------------------------------------------------------------------- /JOS.ApiKeyAuthentication.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28917.182 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JOS.ApiKeyAuthentication.Web", "src\JOS.ApiKeyAuthentication.Web\JOS.ApiKeyAuthentication.Web.csproj", "{F1D175BB-5940-4CA1-BA8D-A2DC8859B8FD}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JOS.ApiKeyAuthentication.Web.Tests", "test\JOS.ApiKeyAuthentication.Web.Tests\JOS.ApiKeyAuthentication.Web.Tests.csproj", "{9EBD5C5D-4CED-4188-99A7-F1783A355D0B}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "misc", "misc", "{7391201F-7150-4899-A34C-2725A6E7E3D5}" 11 | ProjectSection(SolutionItems) = preProject 12 | .github\workflows\dotnet.yml = .github\workflows\dotnet.yml 13 | EndProjectSection 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {F1D175BB-5940-4CA1-BA8D-A2DC8859B8FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {F1D175BB-5940-4CA1-BA8D-A2DC8859B8FD}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {F1D175BB-5940-4CA1-BA8D-A2DC8859B8FD}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {F1D175BB-5940-4CA1-BA8D-A2DC8859B8FD}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {9EBD5C5D-4CED-4188-99A7-F1783A355D0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {9EBD5C5D-4CED-4188-99A7-F1783A355D0B}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {9EBD5C5D-4CED-4188-99A7-F1783A355D0B}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {9EBD5C5D-4CED-4188-99A7-F1783A355D0B}.Release|Any CPU.Build.0 = Release|Any CPU 29 | EndGlobalSection 30 | GlobalSection(SolutionProperties) = preSolution 31 | HideSolutionNode = FALSE 32 | EndGlobalSection 33 | GlobalSection(ExtensibilityGlobals) = postSolution 34 | SolutionGuid = {DF6D9B13-786A-461F-8A04-7A74D3D695D9} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JOS.ApiKeyAuthentication 2 | 3 | https://josef.codes/asp-net-core-protect-your-api-with-api-keys/ 4 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/ApiKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 5 | { 6 | public class ApiKey 7 | { 8 | public ApiKey(int id, string owner, string key, DateTime created, IReadOnlyCollection roles) 9 | { 10 | Id = id; 11 | Owner = owner ?? throw new ArgumentNullException(nameof(owner)); 12 | Key = key ?? throw new ArgumentNullException(nameof(key)); 13 | Created = created; 14 | Roles = roles ?? throw new ArgumentNullException(nameof(roles)); 15 | } 16 | 17 | public int Id { get; } 18 | public string Owner { get; } 19 | public string Key { get; } 20 | public DateTime Created { get; } 21 | public IReadOnlyCollection Roles { get; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/ApiKeyAuthenticationHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Text.Encodings.Web; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | using JOS.ApiKeyAuthentication.Web.Features.Authorization; 9 | using JOS.ApiKeyAuthentication.Web.Features.Json; 10 | using JOS.ApiKeyAuthentication.Web.Features.Shared; 11 | using Microsoft.AspNetCore.Authentication; 12 | using Microsoft.AspNetCore.Http; 13 | using Microsoft.Extensions.Logging; 14 | using Microsoft.Extensions.Options; 15 | 16 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 17 | { 18 | public class ApiKeyAuthenticationHandler : AuthenticationHandler 19 | { 20 | private const string ProblemDetailsContentType = "application/problem+json"; 21 | private readonly IGetApiKeyQuery _getApiKeyQuery; 22 | 23 | public ApiKeyAuthenticationHandler( 24 | IOptionsMonitor options, 25 | ILoggerFactory logger, 26 | UrlEncoder encoder, 27 | IGetApiKeyQuery getApiKeyQuery) : base(options, logger, encoder) 28 | { 29 | _getApiKeyQuery = getApiKeyQuery ?? throw new ArgumentNullException(nameof(getApiKeyQuery)); 30 | } 31 | 32 | protected override async Task HandleAuthenticateAsync() 33 | { 34 | if (!Request.Headers.TryGetValue(ApiKeyConstants.HeaderName, out var apiKeyHeaderValues)) 35 | { 36 | return AuthenticateResult.NoResult(); 37 | } 38 | 39 | var providedApiKey = apiKeyHeaderValues.FirstOrDefault(); 40 | 41 | if (apiKeyHeaderValues.Count == 0 || string.IsNullOrWhiteSpace(providedApiKey)) 42 | { 43 | return AuthenticateResult.NoResult(); 44 | } 45 | 46 | var existingApiKey = await _getApiKeyQuery.Execute(providedApiKey); 47 | 48 | if (existingApiKey != null) 49 | { 50 | var claims = new List 51 | { 52 | new Claim(ClaimTypes.Name, existingApiKey.Owner) 53 | }; 54 | 55 | claims.AddRange(existingApiKey.Roles.Select(role => new Claim(ClaimTypes.Role, role))); 56 | 57 | var identity = new ClaimsIdentity(claims, Options.AuthenticationType); 58 | var identities = new List { identity }; 59 | var principal = new ClaimsPrincipal(identities); 60 | var ticket = new AuthenticationTicket(principal, Options.Scheme); 61 | 62 | return AuthenticateResult.Success(ticket); 63 | } 64 | 65 | return AuthenticateResult.NoResult(); 66 | } 67 | 68 | protected override async Task HandleChallengeAsync(AuthenticationProperties properties) 69 | { 70 | Response.StatusCode = 401; 71 | Response.ContentType = ProblemDetailsContentType; 72 | var problemDetails = new UnauthorizedProblemDetails(); 73 | 74 | await Response.WriteAsync(JsonSerializer.Serialize(problemDetails, DefaultJsonSerializerOptions.Options)); 75 | } 76 | 77 | protected override async Task HandleForbiddenAsync(AuthenticationProperties properties) 78 | { 79 | Response.StatusCode = 403; 80 | Response.ContentType = ProblemDetailsContentType; 81 | var problemDetails = new ForbiddenProblemDetails(); 82 | 83 | await Response.WriteAsync(JsonSerializer.Serialize(problemDetails, DefaultJsonSerializerOptions.Options)); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/ApiKeyAuthenticationOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 4 | { 5 | public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions 6 | { 7 | public const string DefaultScheme = "API Key"; 8 | public string Scheme => DefaultScheme; 9 | public string AuthenticationType = DefaultScheme; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/AuthenticationBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Authentication; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 5 | { 6 | public static class AuthenticationBuilderExtensions 7 | { 8 | public static AuthenticationBuilder AddApiKeySupport(this AuthenticationBuilder authenticationBuilder, Action options) 9 | { 10 | return authenticationBuilder.AddScheme(ApiKeyAuthenticationOptions.DefaultScheme, options); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/IGetApiKeyQuery.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 4 | { 5 | public interface IGetApiKeyQuery 6 | { 7 | Task Execute(string providedApiKey); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/InMemoryGetApiKeyQuery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using JOS.ApiKeyAuthentication.Web.Features.Authorization; 6 | 7 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 8 | { 9 | public class InMemoryGetApiKeyQuery : IGetApiKeyQuery 10 | { 11 | private readonly IDictionary _apiKeys; 12 | 13 | public InMemoryGetApiKeyQuery() 14 | { 15 | var existingApiKeys = new List 16 | { 17 | new ApiKey(1, "Finance", "C5BFF7F0-B4DF-475E-A331-F737424F013C", new DateTime(2019, 01, 01), 18 | new List 19 | { 20 | Roles.Employee, 21 | }), 22 | new ApiKey(2, "Reception", "5908D47C-85D3-4024-8C2B-6EC9464398AD", new DateTime(2019, 01, 01), 23 | new List 24 | { 25 | Roles.Employee 26 | }), 27 | new ApiKey(3, "Management", "06795D9D-A770-44B9-9B27-03C6ABDB1BAE", new DateTime(2019, 01, 01), 28 | new List 29 | { 30 | Roles.Employee, 31 | Roles.Manager 32 | }), 33 | new ApiKey(4, "Some Third Party", "FA872702-6396-45DC-89F0-FC1BE900591B", new DateTime(2019, 06, 01), 34 | new List 35 | { 36 | Roles.ThirdParty 37 | }) 38 | }; 39 | 40 | _apiKeys = existingApiKeys.ToDictionary(x => x.Key, x => x); 41 | } 42 | 43 | public Task Execute(string providedApiKey) 44 | { 45 | _apiKeys.TryGetValue(providedApiKey, out var key); 46 | return Task.FromResult(key); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authentication/UnauthorizedProblemDetails.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authentication 4 | { 5 | public class UnauthorizedProblemDetails : ProblemDetails 6 | { 7 | public UnauthorizedProblemDetails(string details = null) 8 | { 9 | Title = "Unauthorized"; 10 | Detail = details; 11 | Status = 401; 12 | Type = "https://httpstatuses.com/401"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/ForbiddenProblemDetails.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 4 | { 5 | public class ForbiddenProblemDetails : ProblemDetails 6 | { 7 | public ForbiddenProblemDetails(string details = null) 8 | { 9 | Title = "Forbidden"; 10 | Detail = details; 11 | Status = 403; 12 | Type = "https://httpstatuses.com/403"; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyEmployeesAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNetCore.Authorization; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 5 | { 6 | public class OnlyEmployeesAuthorizationHandler : AuthorizationHandler 7 | { 8 | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OnlyEmployeesRequirement requirement) 9 | { 10 | if (context.User.IsInRole(Roles.Employee)) 11 | { 12 | context.Succeed(requirement); 13 | } 14 | 15 | return Task.CompletedTask; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyEmployeesRequirement.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 4 | { 5 | public class OnlyEmployeesRequirement : IAuthorizationRequirement 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyManagersAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNetCore.Authorization; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 5 | { 6 | public class OnlyManagersAuthorizationHandler : AuthorizationHandler 7 | { 8 | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OnlyManagersRequirement requirement) 9 | { 10 | if (context.User.IsInRole(Roles.Manager)) 11 | { 12 | context.Succeed(requirement); 13 | } 14 | 15 | return Task.CompletedTask; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyManagersRequirement.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 4 | { 5 | public class OnlyManagersRequirement : IAuthorizationRequirement 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyThirdPartiesAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNetCore.Authorization; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 5 | { 6 | public class OnlyThirdPartiesAuthorizationHandler : AuthorizationHandler 7 | { 8 | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OnlyThirdPartiesRequirement requirement) 9 | { 10 | if (context.User.IsInRole(Roles.ThirdParty)) 11 | { 12 | context.Succeed(requirement); 13 | } 14 | 15 | return Task.CompletedTask; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/OnlyThirdPartiesRequirement.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 4 | { 5 | public class OnlyThirdPartiesRequirement : IAuthorizationRequirement 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/Policies.cs: -------------------------------------------------------------------------------- 1 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 2 | { 3 | public static class Policies 4 | { 5 | public const string OnlyEmployees = nameof(OnlyEmployees); 6 | public const string OnlyManagers = nameof(OnlyManagers); 7 | public const string OnlyThirdParties = nameof(OnlyThirdParties); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Authorization/Roles.cs: -------------------------------------------------------------------------------- 1 | namespace JOS.ApiKeyAuthentication.Web.Features.Authorization 2 | { 3 | public static class Roles 4 | { 5 | public const string Employee = "Employee"; 6 | public const string Manager = "Manager"; 7 | public const string ThirdParty = "Third Party"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Json/DefaultJsonSerializerOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web.Features.Json 5 | { 6 | public static class DefaultJsonSerializerOptions 7 | { 8 | public static JsonSerializerOptions Options => new() 9 | { 10 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 11 | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull 12 | }; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Shared/ApiKeyConstants.cs: -------------------------------------------------------------------------------- 1 | namespace JOS.ApiKeyAuthentication.Web.Features.Shared 2 | { 3 | public class ApiKeyConstants 4 | { 5 | public const string HeaderName = "X-Api-Key"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/Swagger/SwaggerConfigurator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using JOS.ApiKeyAuthentication.Web.Features.Shared; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.OpenApi.Models; 5 | 6 | namespace JOS.ApiKeyAuthentication.Web.Features.Swagger 7 | { 8 | public static class SwaggerConfigurator 9 | { 10 | public static void ConfigureSwaggerFeature(this IServiceCollection services) 11 | { 12 | services.AddSwaggerGen(c => 13 | { 14 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "JOS.ApiKeyAuthentication", Version = "v1" }); 15 | 16 | c.AddSecurityDefinition(ApiKeyConstants.HeaderName, new OpenApiSecurityScheme 17 | { 18 | Description = "Api key needed to access the endpoints. X-Api-Key: My_API_Key", 19 | In = ParameterLocation.Header, 20 | Name = ApiKeyConstants.HeaderName, 21 | Type = SecuritySchemeType.ApiKey 22 | }); 23 | 24 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 25 | { 26 | { 27 | new OpenApiSecurityScheme 28 | { 29 | Name = ApiKeyConstants.HeaderName, 30 | Type = SecuritySchemeType.ApiKey, 31 | In = ParameterLocation.Header, 32 | Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = ApiKeyConstants.HeaderName }, 33 | }, 34 | new string[] {} 35 | } 36 | }); 37 | }); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Features/User/UserController.cs: -------------------------------------------------------------------------------- 1 | using JOS.ApiKeyAuthentication.Web.Features.Authorization; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace JOS.ApiKeyAuthentication.Web.Features.User 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | [Produces("application/json")] 10 | public class UserController : ControllerBase 11 | { 12 | [HttpGet("anyone")] 13 | public IActionResult Anyone() 14 | { 15 | var message = $"Hello from {nameof(Anyone)}"; 16 | return new ObjectResult(message); 17 | } 18 | 19 | [HttpGet("only-authenticated")] 20 | [Authorize] 21 | public IActionResult OnlyAuthenticated() 22 | { 23 | var message = $"Hello from {nameof(OnlyAuthenticated)}"; 24 | return new ObjectResult(message); 25 | } 26 | 27 | [HttpGet("only-employees")] 28 | [Authorize(Policy = Policies.OnlyEmployees)] 29 | public IActionResult OnlyEmployees() 30 | { 31 | var message = $"Hello from {nameof(OnlyEmployees)}"; 32 | return new ObjectResult(message); 33 | } 34 | 35 | [HttpGet("only-managers")] 36 | [Authorize(Policy = Policies.OnlyManagers)] 37 | public IActionResult OnlyManagers() 38 | { 39 | var message = $"Hello from {nameof(OnlyManagers)}"; 40 | return new ObjectResult(message); 41 | } 42 | 43 | [HttpGet("only-third-parties")] 44 | [Authorize(Policy = Policies.OnlyThirdParties)] 45 | public IActionResult OnlyThirdParties() 46 | { 47 | var message = $"Hello from {nameof(OnlyThirdParties)}"; 48 | return new ObjectResult(message); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/JOS.ApiKeyAuthentication.Web.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | JOS.ApiKeyAuthentication.Web 6 | JOS.ApiKeyAuthentication.Web 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace JOS.ApiKeyAuthentication.Web 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateWebHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 14 | WebHost.CreateDefaultBuilder(args) 15 | .UseStartup(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:51305", 8 | "sslPort": 44391 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": false, 15 | "launchUrl": "api/values", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "ApiKeyAuthentication.Web": { 21 | "commandName": "Project", 22 | "launchBrowser": false, 23 | "launchUrl": "api/values", 24 | "applicationUrl": "http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/Startup.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using System.Text.Json.Serialization; 3 | using JOS.ApiKeyAuthentication.Web.Features.Authentication; 4 | using JOS.ApiKeyAuthentication.Web.Features.Authorization; 5 | using JOS.ApiKeyAuthentication.Web.Features.Swagger; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Hosting; 11 | 12 | namespace JOS.ApiKeyAuthentication.Web 13 | { 14 | public class Startup 15 | { 16 | public Startup(IConfiguration configuration) 17 | { 18 | Configuration = configuration; 19 | } 20 | 21 | public IConfiguration Configuration { get; } 22 | 23 | public void ConfigureServices(IServiceCollection services) 24 | { 25 | services.AddAuthentication(options => 26 | { 27 | options.DefaultAuthenticateScheme = ApiKeyAuthenticationOptions.DefaultScheme; 28 | options.DefaultChallengeScheme = ApiKeyAuthenticationOptions.DefaultScheme; 29 | }).AddApiKeySupport(options => {}); 30 | 31 | services.AddAuthorization(options => 32 | { 33 | options.AddPolicy(Policies.OnlyEmployees, policy => policy.Requirements.Add(new OnlyEmployeesRequirement())); 34 | options.AddPolicy(Policies.OnlyManagers, policy => policy.Requirements.Add(new OnlyManagersRequirement())); 35 | options.AddPolicy(Policies.OnlyThirdParties, policy => policy.Requirements.Add(new OnlyThirdPartiesRequirement())); 36 | }); 37 | 38 | services.AddSingleton(); 39 | services.AddSingleton(); 40 | services.AddSingleton(); 41 | 42 | services.AddSingleton(); 43 | 44 | services.AddRouting(x => x.LowercaseUrls = true); 45 | services.AddControllers() 46 | .AddJsonOptions(options => 47 | { 48 | options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; 49 | options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; 50 | }); 51 | 52 | services.ConfigureSwaggerFeature(); 53 | } 54 | 55 | public void Configure(IApplicationBuilder app, IHostEnvironment env) 56 | { 57 | if (env.IsDevelopment()) 58 | { 59 | app.UseDeveloperExceptionPage(); 60 | } 61 | app.UseRouting(); 62 | app.UseAuthentication(); 63 | app.UseAuthorization(); 64 | 65 | app.UseSwagger(); 66 | app.UseSwaggerUI(c => 67 | { 68 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "JOS.ApiKeyAuthentication"); 69 | }); 70 | 71 | app.UseEndpoints(endpoints => 72 | { 73 | endpoints.MapControllers(); 74 | }); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/JOS.ApiKeyAuthentication.Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /test/JOS.ApiKeyAuthentication.Web.Tests/AuthenticationIntegrationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Mvc.Testing; 7 | using Shouldly; 8 | using Xunit; 9 | 10 | namespace JOS.ApiKeyAuthentication.Web.Tests 11 | { 12 | public class AuthenticationIntegrationTests : IClassFixture> 13 | { 14 | private readonly WebApplicationFactory _factory; 15 | 16 | public AuthenticationIntegrationTests(WebApplicationFactory factory) 17 | { 18 | _factory = factory ?? throw new ArgumentNullException(nameof(factory)); 19 | } 20 | 21 | [Fact] 22 | public async Task GivenUnauthenticatedCall_WhenGetAnyoneEndpoint_ThenReturns200Ok() 23 | { 24 | var httpClient = _factory.CreateClient(); 25 | var request = new HttpRequestMessage(HttpMethod.Get, "api/user/anyone"); 26 | 27 | var response = await httpClient.SendAsync(request); 28 | 29 | response.StatusCode.ShouldBe(HttpStatusCode.OK); 30 | } 31 | 32 | [Theory] 33 | [InlineData("only-authenticated")] 34 | [InlineData("only-employees")] 35 | [InlineData("only-managers")] 36 | [InlineData("only-third-parties")] 37 | public async Task GivenUnauthenticatedCall_WhenGetProtectedEndpoint_ThenReturns401Unauthorized(string action) 38 | { 39 | var httpClient = _factory.CreateClient(); 40 | var request = new HttpRequestMessage(HttpMethod.Get, $"api/user/{action}"); 41 | 42 | var response = await httpClient.SendAsync(request); 43 | var responseContent = await response.Content.ReadAsStringAsync(); 44 | 45 | response.Content.Headers.ContentType.ToString().ShouldBe("application/problem+json"); 46 | responseContent.ShouldBe("{\"type\":\"https://httpstatuses.com/401\",\"title\":\"Unauthorized\",\"status\":401}"); // Really naive check, can't guarantee the order of the properties, but whatever :) 47 | response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); 48 | } 49 | 50 | [Fact] 51 | public async Task GivenAuthenticatedCall_WhenGetOnlyAuthenticated_ThenReturns200Ok() 52 | { 53 | var httpClient = _factory.CreateClient(); 54 | var request = new HttpRequestMessage(HttpMethod.Get, "api/user/only-authenticated"); 55 | var apiKey = "C5BFF7F0-B4DF-475E-A331-F737424F013C"; 56 | request.Headers.Add("X-Api-Key", apiKey); 57 | 58 | var response = await httpClient.SendAsync(request); 59 | var responseContent = await response.Content.ReadAsStringAsync(); 60 | 61 | response.StatusCode.ShouldBe(HttpStatusCode.OK); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /test/JOS.ApiKeyAuthentication.Web.Tests/AuthorizationIntegrationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc.Testing; 6 | using Shouldly; 7 | using Xunit; 8 | 9 | namespace JOS.ApiKeyAuthentication.Web.Tests 10 | { 11 | public class AuthorizationIntegrationTests : IClassFixture> 12 | { 13 | private readonly WebApplicationFactory _factory; 14 | 15 | public AuthorizationIntegrationTests(WebApplicationFactory factory) 16 | { 17 | _factory = factory ?? throw new ArgumentNullException(nameof(factory)); 18 | } 19 | 20 | [Theory] 21 | [InlineData("only-employees")] 22 | [InlineData("only-managers")] 23 | public async Task GivenUnauthorizedCall_WhenGetOnlyEmployees_ThenReturns403Forbidden(string action) 24 | { 25 | var httpClient = _factory.CreateClient(); 26 | var request = new HttpRequestMessage(HttpMethod.Get, $"api/user/{action}"); 27 | var apiKey = "FA872702-6396-45DC-89F0-FC1BE900591B"; // Third party api key 28 | request.Headers.Add("X-Api-Key", apiKey); 29 | 30 | var response = await httpClient.SendAsync(request); 31 | var responseContent = await response.Content.ReadAsStringAsync(); 32 | 33 | response.Content.Headers.ContentType.ToString().ShouldBe("application/problem+json"); 34 | responseContent.ShouldBe("{\"type\":\"https://httpstatuses.com/403\",\"title\":\"Forbidden\",\"status\":403}"); // Really naive check, can't guarantee the order of the properties, but whatever :) 35 | response.StatusCode.ShouldBe(HttpStatusCode.Forbidden); 36 | } 37 | 38 | [Fact] 39 | public async Task GivenAuthorizedCall_WhenGetOnlyThirdParties_ThenReturns200Ok() 40 | { 41 | var httpClient = _factory.CreateClient(); 42 | var request = new HttpRequestMessage(HttpMethod.Get, "api/user/only-third-parties"); 43 | var apiKey = "FA872702-6396-45DC-89F0-FC1BE900591B"; // Third party api key 44 | request.Headers.Add("X-Api-Key", apiKey); 45 | 46 | var response = await httpClient.SendAsync(request); 47 | 48 | response.StatusCode.ShouldBe(HttpStatusCode.OK); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /test/JOS.ApiKeyAuthentication.Web.Tests/JOS.ApiKeyAuthentication.Web.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /test/JOS.ApiKeyAuthentication.Web.Tests/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:53859/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "JOS.ApiKeyAuthentication.Web.Tests": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "environmentVariables": { 22 | "ASPNETCORE_ENVIRONMENT": "Development" 23 | }, 24 | "applicationUrl": "http://localhost:53860/" 25 | } 26 | } 27 | } --------------------------------------------------------------------------------