├── .gitignore
├── ApiKeySample.sln
├── ApiKeySample
├── ApiKeySample.csproj
├── Authentication
│ ├── ApiKeySchemeHandler.cs
│ └── ApiKeySchemeOptions.cs
├── Authorization
│ ├── PermissionAuthorizationHandler.cs
│ ├── PermissionAuthorizationMiddlewareResultHandler.cs
│ └── PermissionRequirement.cs
├── Constants.cs
├── Controllers
│ └── BooksController.cs
├── Extensions
│ ├── AppBuilderExtensions.cs
│ ├── HttpContextExtensions.cs
│ └── ServiceCollectionExtensions.cs
├── Filters
│ ├── PermissionReadAuthorize.cs
│ └── PermissionWriteAuthorize.cs
├── Middleware
│ └── AuthenticationShortCircuitMiddleware.cs
├── Models
│ └── Book.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Security
│ ├── ApiKey.cs
│ ├── CustomClaimTypes.cs
│ └── Customer.cs
├── Services
│ ├── ApiKeyStore.cs
│ ├── ClaimsProvider.cs
│ ├── IApiKeyStore.cs
│ └── IClaimsProvider.cs
├── SwaggerConfigurator.cs
├── appsettings.Development.json
└── appsettings.json
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
352 | .idea/
353 | coverage/*
354 |
355 | oppl-platform.sln.DotSettings
356 |
--------------------------------------------------------------------------------
/ApiKeySample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiKeySample", "ApiKeySample\ApiKeySample.csproj", "{F595750C-6D09-42F4-B2E1-1CF296E041E8}"
4 | EndProject
5 | Global
6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
7 | Debug|Any CPU = Debug|Any CPU
8 | Release|Any CPU = Release|Any CPU
9 | EndGlobalSection
10 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
11 | {F595750C-6D09-42F4-B2E1-1CF296E041E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
12 | {F595750C-6D09-42F4-B2E1-1CF296E041E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
13 | {F595750C-6D09-42F4-B2E1-1CF296E041E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
14 | {F595750C-6D09-42F4-B2E1-1CF296E041E8}.Release|Any CPU.Build.0 = Release|Any CPU
15 | EndGlobalSection
16 | EndGlobal
17 |
--------------------------------------------------------------------------------
/ApiKeySample/ApiKeySample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ApiKeySample/Authentication/ApiKeySchemeHandler.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Claims;
2 | using System.Text.Encodings.Web;
3 | using ApiKeySample.Authorization;
4 | using ApiKeySample.Extensions;
5 | using ApiKeySample.Security;
6 | using ApiKeySample.Services;
7 | using Microsoft.AspNetCore.Authentication;
8 | using Microsoft.AspNetCore.Http.Extensions;
9 | using Microsoft.Extensions.Options;
10 |
11 | namespace ApiKeySample.Authentication;
12 |
13 | public class ApiKeySchemeHandler : AuthenticationHandler
14 | {
15 | private readonly IApiKeyStore _apiKeyStore;
16 | private readonly IClaimsProvider _claimsProvider;
17 |
18 | public ApiKeySchemeHandler(
19 | IOptionsMonitor options,
20 | ILoggerFactory loggerFactory,
21 | UrlEncoder encoder,
22 | ISystemClock clock,
23 | IApiKeyStore apiKeyStore,
24 | IClaimsProvider claimsProvider) : base(options, loggerFactory, encoder, clock)
25 | {
26 | _apiKeyStore = apiKeyStore;
27 | _claimsProvider = claimsProvider;
28 | }
29 |
30 | protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
31 | {
32 | return Task.CompletedTask;
33 | }
34 |
35 | protected override async Task HandleAuthenticateAsync()
36 | {
37 | if (RequestIsNotRequiredToAuthenticateWithApiKey())
38 | {
39 | //This request doesn't required AUTH so pass on the ticket to the middleware
40 | return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), Scheme.Name));
41 | }
42 |
43 | if (!Context.TryGetApiKeyFromQueryParams(out string value))
44 | {
45 | //Missing key the way we want it
46 | return AuthenticateResult.Fail("");
47 | }
48 |
49 | //Let's find our api key based on the parameter
50 | CancellationToken cancellationToken = Context.RequestAborted;
51 | ApiKey? apiKey = await _apiKeyStore.Get(value, cancellationToken);
52 |
53 | if (apiKey is null)
54 | {
55 | //Unrecognized key
56 | return AuthenticateResult.Fail("");
57 | }
58 |
59 | // Generate AuthenticationTicket from the Identity and current authentication scheme
60 | IEnumerable claims = _claimsProvider.GetClaimsFor(apiKey);
61 | ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, nameof(ApiKeySchemeHandler));
62 | AuthenticationTicket ticket = new AuthenticationTicket(new Customer(claimsIdentity, apiKey), this.Scheme.Name);
63 |
64 | // Pass on the ticket to the middleware. All good, main door is open
65 | return AuthenticateResult.Success(ticket);
66 | }
67 |
68 | private bool RequestIsNotRequiredToAuthenticateWithApiKey()
69 | {
70 | return Context.Request.GetDisplayUrl() == "/health";
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/ApiKeySample/Authentication/ApiKeySchemeOptions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication;
2 |
3 | namespace ApiKeySample.Authentication;
4 |
5 | ///
6 | /// Options for our Scheme - Nothing in this case
7 | ///
8 | public class ApiKeySchemeOptions : AuthenticationSchemeOptions
9 | {
10 | }
11 |
--------------------------------------------------------------------------------
/ApiKeySample/Authorization/PermissionAuthorizationHandler.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Claims;
2 | using ApiKeySample.Security;
3 | using Microsoft.AspNetCore.Authorization;
4 |
5 | namespace ApiKeySample.Authorization;
6 |
7 | public class PermissionAuthorizationHandler : AuthorizationHandler
8 | {
9 | protected override Task HandleRequirementAsync(
10 | AuthorizationHandlerContext context,
11 | PermissionRequirement requirement)
12 | {
13 | //Here we check once the api key is authorized to do the action in the specific endpoint
14 | Claim? permissionClaim =
15 | context.User.FindFirst(c =>
16 | c.Type == CustomClaimTypes.Permission && c.Value.Equals(requirement.Permission));
17 |
18 | if (permissionClaim is not null)
19 | {
20 | //It can
21 | context.Succeed(requirement);
22 | }
23 |
24 | //We do nothing.
25 |
26 | return Task.CompletedTask;
27 | }
28 | }
--------------------------------------------------------------------------------
/ApiKeySample/Authorization/PermissionAuthorizationMiddlewareResultHandler.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authorization;
2 | using Microsoft.AspNetCore.Authorization.Policy;
3 |
4 | namespace ApiKeySample.Authorization;
5 |
6 | public class PermissionAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
7 | {
8 | private readonly AuthorizationMiddlewareResultHandler _defaultHandler = new();
9 |
10 | public async Task HandleAsync(
11 | RequestDelegate next,
12 | HttpContext context,
13 | AuthorizationPolicy policy,
14 | PolicyAuthorizationResult authorizeResult)
15 | {
16 | if (authorizeResult.Forbidden
17 | && authorizeResult.AuthorizationFailure!.FailedRequirements
18 | .OfType().Any())
19 | {
20 | // Authenticated, but cannot access the resource => 403
21 | context.Response.StatusCode = StatusCodes.Status403Forbidden;
22 | return;
23 | }
24 |
25 | // Fall back to the default implementation to continue the flow
26 | await _defaultHandler.HandleAsync(next, context, policy, authorizeResult);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/ApiKeySample/Authorization/PermissionRequirement.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authorization;
2 |
3 | namespace ApiKeySample.Authorization;
4 |
5 | ///
6 | /// Our permissions are only Read/Write
7 | ///
8 | ///
9 |
10 | public record PermissionRequirement(string Permission) : IAuthorizationRequirement
11 | {
12 | }
13 |
--------------------------------------------------------------------------------
/ApiKeySample/Constants.cs:
--------------------------------------------------------------------------------
1 | namespace ApiKeySample;
2 |
3 | internal static class Constants
4 | {
5 | internal const string ApiKeyScheme = "ApiKey";
6 |
7 | internal static class Permissions
8 | {
9 | internal const string Read = "r";
10 | internal const string Write = "w";
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/ApiKeySample/Controllers/BooksController.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Filters;
2 | using ApiKeySample.Models;
3 | using Microsoft.AspNetCore.Mvc;
4 |
5 | namespace ApiKeySample.Controllers;
6 |
7 | [ApiController]
8 | [Route("[controller]")]
9 | public class BooksController : ControllerBase
10 | {
11 | private static readonly Dictionary Books = new()
12 | {
13 | {
14 | "9780261103566", new Book()
15 | {
16 | ISBN = "9780261103566",
17 | Author = "J R R Tolkien",
18 | Summary =
19 | "Immerse yourself in Middle-earth with Tolkien's classic masterpiece, telling the complete story of Bilbo Baggins and the Hobbits' epic encounters with Gandalf, Gollum, dragons and monsters, in the quest to destroy the One Ring.",
20 | Title = "The Lord of the Rings And, The Hobbit"
21 | }
22 | },
23 | {
24 | "9780340960196", new Book()
25 | {
26 | ISBN = "9780340960196",
27 | Author = "Frank Herbert",
28 | Summary =
29 | "Before The Matrix, before Star Wars, before Ender's Game and Neuromancer, there was Dune: winner of the prestigious Hugo and Nebula awards, and widely considered one of the greatest science fiction novels ever written.",
30 | Title = "Dune - The Dune Novels"
31 | }
32 | }
33 | };
34 |
35 | [Route("")]
36 | [PermissionReadAuthorize]
37 | [HttpGet]
38 | public IEnumerable Get()
39 | {
40 |
41 | return Books.Values;
42 | }
43 |
44 | [HttpGet]
45 | [Route("{isbn}")]
46 | [PermissionReadAuthorize]
47 | public Book GetByIsbn(string isbn)
48 | {
49 | return Books[isbn];
50 | }
51 |
52 | [Route("")]
53 | [PermissionWriteAuthorize]
54 | [HttpPost]
55 | public ActionResult Post([FromBody] Book body)
56 | {
57 | Books[body.ISBN] = body;
58 | return Created(nameof(GetByIsbn), body.ISBN);
59 | }
60 | }
--------------------------------------------------------------------------------
/ApiKeySample/Extensions/AppBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Middleware;
2 |
3 | namespace ApiKeySample.Extensions;
4 |
5 | internal static class AppBuilderExtensions
6 | {
7 | internal static IApplicationBuilder UseAuthenticationShortCircuit(this IApplicationBuilder builder)
8 | {
9 | builder.UseMiddleware();
10 | return builder;
11 | }
12 | }
--------------------------------------------------------------------------------
/ApiKeySample/Extensions/HttpContextExtensions.cs:
--------------------------------------------------------------------------------
1 |
2 | using Microsoft.Extensions.Primitives;
3 |
4 | namespace ApiKeySample.Extensions;
5 |
6 | internal static class HttpContextExtensions
7 | {
8 | internal static bool TryGetApiKeyFromQueryParams(this HttpContext context, out string parsedApiKey)
9 | {
10 | parsedApiKey = string.Empty;
11 | if (!context.Request.Query.TryGetValue("api_key", out StringValues header))
12 | {
13 | return false;
14 | }
15 |
16 | if (!header.Any())
17 | {
18 | return false;
19 | }
20 |
21 | parsedApiKey = header.First()!;
22 | return !string.IsNullOrWhiteSpace(parsedApiKey);
23 | }
24 | }
--------------------------------------------------------------------------------
/ApiKeySample/Extensions/ServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Authentication;
2 | using ApiKeySample.Authorization;
3 | using ApiKeySample.Services;
4 | using Microsoft.AspNetCore.Authorization;
5 | using Microsoft.OpenApi.Models;
6 | using Swashbuckle.AspNetCore.SwaggerGen;
7 |
8 | namespace ApiKeySample.Extensions;
9 |
10 | internal static class ServiceCollectionExtensions
11 | {
12 | internal static IServiceCollection AddApiKey(this IServiceCollection services)
13 | {
14 | services
15 | .AddAuthentication(x =>
16 | {
17 | x.DefaultAuthenticateScheme = Constants.ApiKeyScheme;
18 | x.DefaultChallengeScheme = Constants.ApiKeyScheme;
19 | })
20 | .AddScheme(
21 | Constants.ApiKeyScheme,
22 | Constants.ApiKeyScheme,
23 | null);
24 |
25 | services.AddAuthorization(options =>
26 | {
27 | options.DefaultPolicy = new AuthorizationPolicyBuilder()
28 | .RequireAuthenticatedUser()
29 | .Build();
30 |
31 | options.AddPolicy(
32 | Constants.Permissions.Read,
33 | policy => policy.Requirements.Add(new PermissionRequirement(Constants.Permissions.Read)));
34 |
35 | options.AddPolicy(
36 | Constants.Permissions.Write,
37 | policy => policy.Requirements.Add(new PermissionRequirement(Constants.Permissions.Write)));
38 | });
39 |
40 |
41 | services
42 | .AddSingleton()
43 | .AddSingleton()
44 | .AddSingleton()
45 | .AddSingleton();
46 |
47 | return services;
48 | }
49 | }
--------------------------------------------------------------------------------
/ApiKeySample/Filters/PermissionReadAuthorize.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authorization;
2 |
3 | namespace ApiKeySample.Filters;
4 |
5 | public class PermissionReadAuthorize : AuthorizeAttribute
6 | {
7 | public PermissionReadAuthorize()
8 | {
9 | Policy = Constants.Permissions.Read;
10 | }
11 |
12 | }
--------------------------------------------------------------------------------
/ApiKeySample/Filters/PermissionWriteAuthorize.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authorization;
2 |
3 | namespace ApiKeySample.Filters;
4 |
5 | public class PermissionWriteAuthorize : AuthorizeAttribute
6 | {
7 | public PermissionWriteAuthorize()
8 | {
9 | Policy = Constants.Permissions.Write;
10 | }
11 | }
--------------------------------------------------------------------------------
/ApiKeySample/Middleware/AuthenticationShortCircuitMiddleware.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 |
3 | namespace ApiKeySample.Middleware;
4 |
5 | public class AuthenticationShortCircuitMiddleware
6 | {
7 | private readonly RequestDelegate _next;
8 |
9 | public AuthenticationShortCircuitMiddleware(RequestDelegate next)
10 | {
11 | _next = next;
12 | }
13 |
14 | public async Task InvokeAsync(HttpContext context)
15 | {
16 | if (context.User.Identity is not null && context.User.Identity.IsAuthenticated)
17 | {
18 | await _next(context);
19 | }
20 | else
21 | {
22 | context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ApiKeySample/Models/Book.cs:
--------------------------------------------------------------------------------
1 | namespace ApiKeySample.Models;
2 |
3 | public class Book
4 | {
5 | public string ISBN { get; set; }
6 |
7 | public string Title { get; set; }
8 |
9 | public string Author { get; set; }
10 |
11 | public string? Summary { get; set; }
12 | }
--------------------------------------------------------------------------------
/ApiKeySample/Program.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Extensions;
2 |
3 | WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
4 |
5 | IServiceCollection services = builder.Services;
6 |
7 | services.AddControllers();
8 | services
9 | .AddEndpointsApiExplorer()
10 | .AddSwaggerGen(SwaggerConfigurator.Configure)
11 | .AddApiKey();
12 |
13 | WebApplication app = builder.Build();
14 |
15 | app
16 | .UseSwagger()
17 | .UseSwaggerUI()
18 | .UseAuthentication()
19 | .UseAuthenticationShortCircuit()
20 | .UseAuthorization();
21 |
22 | app.MapControllers();
23 |
24 | app.Run();
--------------------------------------------------------------------------------
/ApiKeySample/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "profiles": {
4 | "http": {
5 | "commandName": "Project",
6 | "dotnetRunMessages": true,
7 | "launchBrowser": true,
8 | "launchUrl": "swagger",
9 | "applicationUrl": "http://localhost:5000",
10 | "environmentVariables": {
11 | "ASPNETCORE_ENVIRONMENT": "Development"
12 | }
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ApiKeySample/Security/ApiKey.cs:
--------------------------------------------------------------------------------
1 | namespace ApiKeySample.Security;
2 |
3 |
4 | ///
5 | /// The ApiKey, this can be loaded from any type of Store: DB/Cache
6 | ///
7 | public class ApiKey
8 | {
9 | public ApiKey(string key, Guid companyId, string permissions)
10 | {
11 | Key = key;
12 | CompanyId = companyId;
13 | Permissions = permissions.Select(x => x.ToString()).ToArray();
14 | }
15 |
16 | public string Key { get; }
17 |
18 | public Guid CompanyId { get; }
19 | public string[] Permissions { get; }
20 | }
--------------------------------------------------------------------------------
/ApiKeySample/Security/CustomClaimTypes.cs:
--------------------------------------------------------------------------------
1 | namespace ApiKeySample.Security;
2 |
3 | internal static class CustomClaimTypes
4 | {
5 | internal const string Permission = "x-permission";
6 | }
7 |
--------------------------------------------------------------------------------
/ApiKeySample/Security/Customer.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Claims;
2 | using System.Security.Principal;
3 |
4 | namespace ApiKeySample.Security;
5 |
6 | ///
7 | /// A logged in Principal that abstract claims
8 | ///
9 | public class Customer : ClaimsPrincipal
10 | {
11 | private readonly ApiKey _apiKey;
12 |
13 | public Customer(IIdentity principal, ApiKey apiKey)
14 | : base(principal)
15 | {
16 | _apiKey = apiKey;
17 | }
18 |
19 | public string Id => _apiKey.Key;
20 |
21 | public Guid CompanyId => _apiKey.CompanyId;
22 |
23 | public bool CanWrite() =>
24 | Claims.Any(x => x is { Type: CustomClaimTypes.Permission, Value: Constants.Permissions.Write });
25 |
26 | public bool CanRead() =>
27 | Claims.Any(x => x is { Type: CustomClaimTypes.Permission, Value: Constants.Permissions.Read });
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/ApiKeySample/Services/ApiKeyStore.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Authorization;
2 | using ApiKeySample.Security;
3 |
4 | namespace ApiKeySample.Services;
5 |
6 | internal class ApiKeyStore : IApiKeyStore
7 | {
8 | private static Guid ReadWrite = Guid.Parse("00000000-0000-0000-0000-000000000000");
9 | private static Guid ReadOnly = Guid.Parse("00000000-0000-0000-0000-000000000001");
10 |
11 | private Dictionary _keys = new()
12 | {
13 | { $"{ReadWrite}", new ApiKey($"{ReadWrite}", ReadWrite, "rw") },
14 | { $"{ReadOnly}", new ApiKey($"{ReadOnly}", ReadOnly, "r") },
15 | };
16 |
17 | public Task Get(string apiKey, CancellationToken cancellationToken)
18 | {
19 | _keys.TryGetValue(apiKey, out ApiKey? key);
20 | return Task.FromResult(key);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ApiKeySample/Services/ClaimsProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Claims;
2 | using ApiKeySample.Authorization;
3 | using ApiKeySample.Security;
4 |
5 | namespace ApiKeySample.Services;
6 |
7 | internal class ClaimsProvider : IClaimsProvider
8 | {
9 | public IEnumerable GetClaimsFor(ApiKey apiKey)
10 | {
11 | return
12 | apiKey
13 | .Permissions
14 | .Select(c => c switch
15 | {
16 | Constants.Permissions.Read => new Claim(CustomClaimTypes.Permission, Constants.Permissions.Read),
17 | Constants.Permissions.Write => new Claim(CustomClaimTypes.Permission, Constants.Permissions.Write),
18 | _ => throw new ArgumentException()
19 | });
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/ApiKeySample/Services/IApiKeyStore.cs:
--------------------------------------------------------------------------------
1 | using ApiKeySample.Authorization;
2 | using ApiKeySample.Security;
3 |
4 | namespace ApiKeySample.Services;
5 |
6 | public interface IApiKeyStore
7 | {
8 | Task Get(string apiKey, CancellationToken cancellationToken);
9 | }
--------------------------------------------------------------------------------
/ApiKeySample/Services/IClaimsProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Claims;
2 | using ApiKeySample.Authorization;
3 | using ApiKeySample.Security;
4 |
5 | namespace ApiKeySample.Services;
6 |
7 | public interface IClaimsProvider
8 | {
9 | IEnumerable GetClaimsFor(ApiKey apiKey);
10 | }
--------------------------------------------------------------------------------
/ApiKeySample/SwaggerConfigurator.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.OpenApi.Models;
2 | using Swashbuckle.AspNetCore.SwaggerGen;
3 |
4 | internal static class SwaggerConfigurator
5 | {
6 | internal static void Configure(SwaggerGenOptions x)
7 | {
8 | OpenApiSecurityScheme queryScheme = new OpenApiSecurityScheme
9 | {
10 | Name = "api_key",
11 | Description = "Api Key Authentication",
12 | In = ParameterLocation.Query,
13 | Type = SecuritySchemeType.ApiKey,
14 | Reference = new OpenApiReference { Id = "Query", Type = ReferenceType.SecurityScheme }
15 | };
16 |
17 | x.AddSecurityDefinition(queryScheme.Reference.Id, queryScheme);
18 | x.AddSecurityRequirement(new OpenApiSecurityRequirement { { queryScheme, Array.Empty() }, });
19 | }
20 | }
--------------------------------------------------------------------------------
/ApiKeySample/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/ApiKeySample/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | },
8 | "AllowedHosts": "*"
9 | }
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ApiKeySample
2 | 6 words cheatsheet:
3 |
4 | ```
5 | AUTHENTICATION (WHO) => MIDDLEWARE
6 | AUTHORIZATION (WHAT)=> FILTERS
7 | ```
8 |
--------------------------------------------------------------------------------