Skip to content

Commit 8e812e8

Browse files
authored
Merge pull request #40 from mihirdilip/8.0.0
8.0.0
2 parents 0e7f017 + e6fa978 commit 8e812e8

File tree

45 files changed

+858
-190
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+858
-190
lines changed

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2022 Mihir Dilip
3+
Copyright (c) 2023 Mihir Dilip
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Easy to use and very light weight Microsoft style API Key Authentication Impleme
77

88
## .NET (Core) Frameworks Supported
99
.NET Framework 4.6.1 and/or NetStandard 2.0 onwards
10-
Multi targeted: net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
10+
Multi targeted: net8.0; net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
1111

1212
<br/>
1313

@@ -380,6 +380,7 @@ public void ConfigureServices(IServiceCollection services)
380380
## Release Notes
381381
| Version | &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Notes |
382382
|---------|-------|
383+
|8.0.0 | <ul><li>net8.0 support added</li><li>Sample project for net8.0 added</li><li>ApiKeySamplesClient.http file added for testing sample projects</li><li>Readme updated</li></ul> |
383384
|7.0.0 | <ul><li>net7.0 support added</li><li>Information log on handler is changed to Debug log when API Key is not found on the request</li><li>Added package validations</li><li>Sample project for net7.0 added</li><li>Readme updated</li><li>Readme added to package</li></ul> |
384385
|6.0.1 | <ul><li>net6.0 support added</li><li>Information log on handler is changed to Debug log when IgnoreAuthenticationIfAllowAnonymous is enabled</li><li>Sample project added</li><li>Readme updated</li><li>Copyright year updated on License</li></ul> |
385386
|5.1.0 | <ul><li>WWW-Authenticate challenge header now returns SchemeName as scheme part instead of ApiKeyOptions.KeyName</li><li>WWW-Authenticate challenge header now has 2 new parameters 'in' and 'key_name' in value part</li><li>ForLegacyUseKeyNameAsSchemeNameOnWWWAuthenticateHeader added to the ApiKeyOptions</li><li>In Authorization Header now able to use either SchemeName or ApiKeyOptions.KeyName when matching AuthorizationHeader Scheme</li><li>Visibility of all the handlers changed to public [#21](https://github.com/mihirdilip/aspnetcore-authentication-apikey/issues/21)</li><li>Tests added</li><li>Readme updated</li><li>Copyright year updated on License</li></ul> |

samples/ApiKeySamplesClient.http

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
@HostAddress = https://localhost:44304
2+
@ApiKey = Key1
3+
4+
# Get Values No Auth
5+
GET {{HostAddress}}/api/values
6+
Accept: application/json
7+
8+
###
9+
10+
# Get Values
11+
GET {{HostAddress}}/api/values
12+
Accept: application/json
13+
X-API-Key: {{ApiKey}}
14+
15+
###
16+
17+
# Claims
18+
GET {{HostAddress}}/api/values/claims
19+
Accept: application/json
20+
X-API-Key: {{ApiKey}}
21+
22+
###
23+
24+
# Forbid
25+
GET {{HostAddress}}/api/values/forbid
26+
Accept: application/json
27+
X-API-Key: {{ApiKey}}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// This file is used by Code Analysis to maintain SuppressMessage
2+
// attributes that are applied to this project.
3+
// Project-level suppressions either have no target or are given
4+
// a specific target and scoped to a namespace, type, member, etc.
5+
6+
using System.Diagnostics.CodeAnalysis;
7+
8+
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "<Pending>", Scope = "member", Target = "~F:SampleWebApi.Repositories.InMemoryApiKeyRepository._cache")]
9+
[assembly: SuppressMessage("Style", "IDE0090:Use 'new(...)'", Justification = "<Pending>", Scope = "member", Target = "~F:SampleWebApi.Repositories.InMemoryApiKeyRepository._cache")]
10+
[assembly: SuppressMessage("Style", "IDE0290:Use primary constructor", Justification = "<Pending>", Scope = "member", Target = "~M:SampleWebApi.Models.ApiKey.#ctor(System.String,System.String,System.Collections.Generic.List{System.Security.Claims.Claim})")]
11+
[assembly: SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "<Pending>", Scope = "member", Target = "~M:SampleWebApi.Models.ApiKey.#ctor(System.String,System.String,System.Collections.Generic.List{System.Security.Claims.Claim})")]
12+
[assembly: SuppressMessage("Style", "IDE0290:Use primary constructor", Justification = "<Pending>", Scope = "member", Target = "~M:SampleWebApi.Services.ApiKeyProvider.#ctor(Microsoft.Extensions.Logging.ILogger{AspNetCore.Authentication.ApiKey.IApiKeyProvider},SampleWebApi.Repositories.IApiKeyRepository)")]
13+
14+
[assembly: SuppressMessage("Usage", "CA2254:Template should be a static expression", Justification = "<Pending>", Scope = "member", Target = "~M:SampleWebApi.Services.ApiKeyProvider.ProvideAsync(System.String)~System.Threading.Tasks.Task{AspNetCore.Authentication.ApiKey.IApiKey}")]
15+
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
using AspNetCore.Authentication.ApiKey;
1+
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
2+
using AspNetCore.Authentication.ApiKey;
23
using System.Collections.Generic;
34
using System.Security.Claims;
45

56
namespace SampleWebApi.Models
67
{
78
class ApiKey : IApiKey
89
{
9-
public ApiKey(string key, string owner, List<Claim> claims = null)
10-
{
10+
public ApiKey(string key, string owner, List<Claim> claims = null)
11+
{
1112
Key = key;
1213
OwnerName = owner;
1314
Claims = claims ?? new List<Claim>();
@@ -18,3 +19,4 @@ public ApiKey(string key, string owner, List<Claim> claims = null)
1819
public IReadOnlyCollection<Claim> Claims { get; }
1920
}
2021
}
22+
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.

samples/SampleWebApi.Shared/Repositories/IApiKeyRepository.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ namespace SampleWebApi.Repositories
88
/// </summary>
99
public interface IApiKeyRepository
1010
{
11-
Task<IApiKey> GetApiKeyAsync(string key);
11+
Task<IApiKey> GetApiKeyAsync(string key);
1212
}
1313
}
Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using AspNetCore.Authentication.ApiKey;
1+
#pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type.
2+
using AspNetCore.Authentication.ApiKey;
23
using SampleWebApi.Models;
34
using System;
45
using System.Collections.Generic;
@@ -7,21 +8,22 @@
78

89
namespace SampleWebApi.Repositories
910
{
10-
/// <summary>
11-
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
12-
/// </summary>
13-
public class InMemoryApiKeyRepository : IApiKeyRepository
11+
/// <summary>
12+
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
13+
/// </summary>
14+
public class InMemoryApiKeyRepository : IApiKeyRepository
1415
{
15-
private List<IApiKey> _cache = new List<IApiKey>
16-
{
16+
private readonly List<IApiKey> _cache = new List<IApiKey>()
17+
{
1718
new ApiKey("Key1", "Admin"),
1819
new ApiKey("Key2", "User"),
1920
};
2021

2122
public Task<IApiKey> GetApiKeyAsync(string key)
2223
{
2324
var apiKey = _cache.FirstOrDefault(k => k.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
24-
return Task.FromResult(apiKey);
25-
}
26-
}
25+
return Task.FromResult(apiKey);
26+
}
27+
}
2728
}
29+
#pragma warning restore CS8619 // Nullability of reference types in value doesn't match target type.

samples/SampleWebApi.Shared/SampleWebApi.Shared.projitems

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
<Import_RootNamespace>SampleWebApi.Shared</Import_RootNamespace>
1010
</PropertyGroup>
1111
<ItemGroup>
12+
<Compile Include="$(MSBuildThisFileDirectory)GlobalSuppressions.cs" />
1213
<Compile Include="$(MSBuildThisFileDirectory)Models\ApiKey.cs" />
1314
<Compile Include="$(MSBuildThisFileDirectory)Services\ApiKeyProvider.cs" />
1415
<Compile Include="$(MSBuildThisFileDirectory)Repositories\InMemoryApiKeyRepository.cs" />

samples/SampleWebApi_2_0/SampleWebApi_2_0.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.0</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
6+
<NuGetAudit>false</NuGetAudit>
57
</PropertyGroup>
68

79
<ItemGroup>

samples/SampleWebApi_2_2/SampleWebApi_2_2.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.2</TargetFramework>
55
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
6+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
7+
<NuGetAudit>false</NuGetAudit>
68
</PropertyGroup>
79

810
<ItemGroup>

samples/SampleWebApi_3_1/SampleWebApi_3_1.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
56
</PropertyGroup>
67

78
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />

samples/SampleWebApi_5_0/SampleWebApi_5_0.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>net5.0</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
56
</PropertyGroup>
67

78
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System.Text;
4+
5+
namespace SampleWebApi_8_0.Controllers
6+
{
7+
[Route("api/[controller]")]
8+
[ApiController]
9+
public class ValuesController : ControllerBase
10+
{
11+
// GET api/values
12+
[AllowAnonymous]
13+
[HttpGet]
14+
public ActionResult<IEnumerable<string>> Get()
15+
{
16+
return new string[] { "value1", "value2" };
17+
}
18+
19+
[HttpGet("claims")]
20+
public ActionResult<string> Claims()
21+
{
22+
var sb = new StringBuilder();
23+
foreach (var claim in User.Claims)
24+
{
25+
sb.AppendLine($"{claim.Type}: {claim.Value}");
26+
}
27+
return sb.ToString();
28+
}
29+
30+
[HttpGet("forbid")]
31+
public new IActionResult Forbid()
32+
{
33+
return base.Forbid();
34+
}
35+
}
36+
}

samples/SampleWebApi_8_0/Program.cs

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
using AspNetCore.Authentication.ApiKey;
2+
using Microsoft.AspNetCore.Authorization;
3+
using SampleWebApi.Repositories;
4+
using SampleWebApi.Services;
5+
6+
var builder = WebApplication.CreateBuilder(args);
7+
8+
// Add User repository to the dependency container.
9+
builder.Services.AddTransient<IApiKeyRepository, InMemoryApiKeyRepository>();
10+
11+
// Add the ApiKey scheme authentication here..
12+
// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
13+
// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider.
14+
builder.Services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)
15+
16+
// The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register.
17+
// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.*
18+
//.AddApiKeyInHeaderOrQueryParams(options =>
19+
20+
// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register.
21+
// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.
22+
.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options =>
23+
{
24+
options.Realm = "Sample Web API";
25+
options.KeyName = "X-API-KEY";
26+
27+
//// Optional option to suppress the browser login dialog for ajax calls.
28+
//options.SuppressWWWAuthenticateHeader = true;
29+
30+
//// Optional option to ignore extra check of ApiKey string after it is validated.
31+
//options.ForLegacyIgnoreExtraValidatedApiKeyCheck = true;
32+
33+
//// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint.
34+
//options.IgnoreAuthenticationIfAllowAnonymous = true;
35+
36+
//// Optional events to override the ApiKey original logic with custom logic.
37+
//// Only use this if you know what you are doing at your own risk. Any of the events can be assigned.
38+
options.Events = new ApiKeyEvents
39+
{
40+
41+
//// A delegate assigned to this property will be invoked just before validating the api key.
42+
//OnValidateKey = async (context) =>
43+
//{
44+
// // custom code to handle the api key, create principal and call Success method on context.
45+
// var apiKeyRepository = context.HttpContext.RequestServices.GetRequiredService<IApiKeyRepository>();
46+
// var apiKey = await apiKeyRepository.GetApiKeyAsync(context.ApiKey);
47+
// var isValid = apiKey != null && apiKey.Key.Equals(context.ApiKey, StringComparison.OrdinalIgnoreCase);
48+
// if (isValid)
49+
// {
50+
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateKey");
51+
// var claims = new[]
52+
// {
53+
// new Claim(ClaimTypes.NameIdentifier, apiKey.OwnerName, ClaimValueTypes.String, context.Options.ClaimsIssuer),
54+
// new Claim(ClaimTypes.Name, apiKey.OwnerName, ClaimValueTypes.String, context.Options.ClaimsIssuer),
55+
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateKey")
56+
// };
57+
// context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
58+
// context.Success();
59+
// }
60+
// else
61+
// {
62+
// context.NoResult();
63+
// }
64+
//},
65+
66+
//// A delegate assigned to this property will be invoked just before validating the api key.
67+
//// NOTE: Same as above delegate but slightly different implementation which will give same result.
68+
//OnValidateKey = async (context) =>
69+
//{
70+
// // custom code to handle the api key, create principal and call Success method on context.
71+
// var apiKeyRepository = context.HttpContext.RequestServices.GetRequiredService<IApiKeyRepository>();
72+
// var apiKey = await apiKeyRepository.GetApiKeyAsync(context.ApiKey);
73+
// var isValid = apiKey != null && apiKey.Key.Equals(context.ApiKey, StringComparison.OrdinalIgnoreCase);
74+
// if (isValid)
75+
// {
76+
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateKey");
77+
// var claims = new[]
78+
// {
79+
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateKey")
80+
// };
81+
// context.ValidationSucceeded(apiKey.OwnerName, claims); // claims are optional
82+
// }
83+
// else
84+
// {
85+
// context.ValidationFailed();
86+
// }
87+
//},
88+
89+
//// A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
90+
//OnHandleChallenge = async (context) =>
91+
//{
92+
// // custom code to handle authentication challenge unauthorized response.
93+
// context.Response.StatusCode = StatusCodes.Status401Unauthorized;
94+
// context.Response.Headers.Add("ChallengeCustomHeader", "From OnHandleChallenge");
95+
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleChallenge\"}");
96+
// context.Handled(); // important! do not forget to call this method at the end.
97+
//},
98+
99+
//// A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
100+
//OnHandleForbidden = async (context) =>
101+
//{
102+
// // custom code to handle forbidden response.
103+
// context.Response.StatusCode = StatusCodes.Status403Forbidden;
104+
// context.Response.Headers.Add("ForbidCustomHeader", "From OnHandleForbidden");
105+
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleForbidden\"}");
106+
// context.Handled(); // important! do not forget to call this method at the end.
107+
//},
108+
109+
//// A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateKey delegate is assigned.
110+
//// It can be used for adding claims, headers, etc to the response.
111+
//OnAuthenticationSucceeded = (context) =>
112+
//{
113+
// //custom code to add extra bits to the success response.
114+
// context.Response.Headers.Add("SuccessCustomHeader", "From OnAuthenticationSucceeded");
115+
// var customClaims = new List<Claim>
116+
// {
117+
// new Claim("CustomClaimType", "Custom Claim Value - from OnAuthenticationSucceeded")
118+
// };
119+
// context.AddClaims(customClaims);
120+
// //or can add like this - context.Principal.AddIdentity(new ClaimsIdentity(customClaims));
121+
// return Task.CompletedTask;
122+
//},
123+
124+
//// A delegate assigned to this property will be invoked when the authentication fails.
125+
//OnAuthenticationFailed = (context) =>
126+
//{
127+
// // custom code to handle failed authentication.
128+
// context.Fail("Failed to authenticate");
129+
// return Task.CompletedTask;
130+
//}
131+
132+
};
133+
});
134+
135+
builder.Services.AddControllers(options =>
136+
{
137+
// ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication.
138+
//options.Filters.Add<RequireHttpsAttribute>();
139+
140+
}); //.AddXmlSerializerFormatters() // To enable XML along with JSON;
141+
142+
// All the requests will need to be authorized.
143+
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
144+
builder.Services.AddAuthorizationBuilder()
145+
.AddFallbackPolicy(
146+
"FallbackPolicy",
147+
new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()
148+
);
149+
150+
var app = builder.Build();
151+
152+
// Configure the HTTP request pipeline.
153+
154+
app.UseHttpsRedirection();
155+
156+
app.UseAuthentication(); // NOTE: DEFAULT TEMPLATE DOES NOT HAVE THIS, THIS LINE IS REQUIRED AND HAS TO BE ADDED!!!
157+
158+
app.UseAuthorization();
159+
160+
app.MapControllers();
161+
162+
app.Run();

0 commit comments

Comments
 (0)