Skip to content

Commit 0d0dc9b

Browse files
committed
- IgnoreAuthenticationIfAllowAnonymous option added
- Samples updated - Readme updated
1 parent 79c9bae commit 0d0dc9b

File tree

10 files changed

+85
-32
lines changed

10 files changed

+85
-32
lines changed

README.md

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ public class Startup
5454
services.AddControllers();
5555

5656
//// By default, authentication is not challenged for every request which is ASP.NET Core's default intended behaviour.
57-
//// So to challenge authentication for every requests please use below option instead of above services.AddControllers().
58-
//services.AddControllers(options =>
59-
//{
60-
// options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
61-
//});
57+
//// So to challenge authentication for every requests please use below FallbackPolicy option.
58+
//services.AddAuthorization(options =>
59+
//{
60+
// options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
61+
//});
6262
}
6363

6464
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
@@ -178,16 +178,20 @@ Required to be set. It is the name of the header if it is setup as in-header or
178178
#### Realm
179179
Required to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.
180180

181-
#### ForLegacyIgnoreExtraValidatedApiKeyCheck
182-
Default value is false.
183-
If set to true, IApiKey.Key property returned from IApiKeyProvider.ProvideAsync(string) method is not compared with the key parsed from the request.
184-
This extra check did not existed in the previous version. So you if want to revert back to old version validation, please set this to true.
185-
186181
#### SuppressWWWAuthenticateHeader
187182
Default value is false.
188183
When set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.
189184
When set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.
190185

186+
#### IgnoreAuthenticationIfAllowAnonymous
187+
Default value is false.
188+
If set to true, it checks if AllowAnonymous filter on controller action or metadata on the endpoint which, if found, it does not try to authenticate the request.
189+
190+
#### ForLegacyIgnoreExtraValidatedApiKeyCheck
191+
Default value is false.
192+
If set to true, IApiKey.Key property returned from IApiKeyProvider.ProvideAsync(string) method is not compared with the key parsed from the request.
193+
This extra check did not existed in the previous version. So you if want to revert back to old version validation, please set this to true.
194+
191195
#### Events
192196
The object provided by the application to process events raised by the api key authentication middleware.
193197
The application may implement the interface fully, or it may create an instance of ApiKeyEvents and assign delegates only to the events it wants to process.
@@ -222,9 +226,9 @@ Please note that, by default, with ASP.NET Core, all the requests are not challe
222226
However, if you want all the requests to challenge authentication by default, depending on what you are using, you can add the below options line to *ConfigureServices* method on *Startup* class.
223227

224228
```C#
225-
services.AddControllers(options =>
226-
{
227-
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
229+
services.AddAuthorization(options =>
230+
{
231+
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
228232
});
229233

230234
// OR

samples/SampleWebApi_2_0/SampleWebApi_2_0.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
</ItemGroup>
1313

1414
<ItemGroup>
15-
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="3.1.1" />
15+
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="5.0.0" />
1616
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
1717
</ItemGroup>
1818

samples/SampleWebApi_2_2/SampleWebApi_2_2.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
</PropertyGroup>
77

88
<ItemGroup>
9-
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="3.1.1" />
9+
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="5.0.0" />
1010
<PackageReference Include="Microsoft.AspNetCore.App" />
1111
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
1212
</ItemGroup>

samples/SampleWebApi_3_1/SampleWebApi_3_1.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
88

99
<ItemGroup>
10-
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="3.1.1" />
10+
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="5.0.0" />
1111
</ItemGroup>
1212

1313
<!--<ItemGroup>

samples/SampleWebApi_3_1/Startup.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ public void ConfigureServices(IServiceCollection services)
5050
//// Optional option to suppress the browser login dialog for ajax calls.
5151
//options.SuppressWWWAuthenticateHeader = true;
5252

53+
//// Optional option to ignore extra check of ApiKey string after it is validated.
54+
//options.ForLegacyIgnoreExtraValidatedApiKeyCheck = true;
55+
56+
//// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint.
57+
//options.IgnoreAuthenticationIfAllowAnonymous = true;
58+
5359
//// Optional events to override the ApiKey original logic with custom logic.
5460
//// Only use this if you know what you are doing at your own risk. Any of the events can be assigned.
5561
options.Events = new ApiKeyEvents
@@ -154,10 +160,16 @@ public void ConfigureServices(IServiceCollection services)
154160
// ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication.
155161
//options.Filters.Add<RequireHttpsAttribute>();
156162

157-
// All the requests will need to be authorized.
158-
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
159-
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
160163
}); //.AddXmlSerializerFormatters() // To enable XML along with JSON;
164+
165+
// All the requests will need to be authorized.
166+
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
167+
services.AddAuthorization(options =>
168+
{
169+
options.FallbackPolicy = new AuthorizationPolicyBuilder()
170+
.RequireAuthenticatedUser()
171+
.Build();
172+
});
161173
}
162174

163175
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

samples/SampleWebApi_5_0/SampleWebApi_5_0.csproj

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66

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

9-
<!--<ItemGroup>
10-
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="3.1.1" />
11-
</ItemGroup>-->
12-
139
<ItemGroup>
14-
<ProjectReference Include="..\..\src\AspNetCore.Authentication.ApiKey\AspNetCore.Authentication.ApiKey.csproj" />
10+
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="5.0.0" />
1511
</ItemGroup>
1612

13+
<!--<ItemGroup>
14+
<ProjectReference Include="..\..\src\AspNetCore.Authentication.ApiKey\AspNetCore.Authentication.ApiKey.csproj" />
15+
</ItemGroup>-->
16+
1717
</Project>

samples/SampleWebApi_5_0/Startup.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
using AspNetCore.Authentication.ApiKey;
23
using Microsoft.AspNetCore.Authorization;
34
using Microsoft.AspNetCore.Builder;
@@ -50,6 +51,12 @@ public void ConfigureServices(IServiceCollection services)
5051
//// Optional option to suppress the browser login dialog for ajax calls.
5152
//options.SuppressWWWAuthenticateHeader = true;
5253

54+
//// Optional option to ignore extra check of ApiKey string after it is validated.
55+
//options.ForLegacyIgnoreExtraValidatedApiKeyCheck = true;
56+
57+
//// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint.
58+
//options.IgnoreAuthenticationIfAllowAnonymous = true;
59+
5360
//// Optional events to override the ApiKey original logic with custom logic.
5461
//// Only use this if you know what you are doing at your own risk. Any of the events can be assigned.
5562
options.Events = new ApiKeyEvents
@@ -154,10 +161,16 @@ public void ConfigureServices(IServiceCollection services)
154161
// ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication.
155162
//options.Filters.Add<RequireHttpsAttribute>();
156163

157-
// All the requests will need to be authorized.
158-
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
159-
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
160164
}); //.AddXmlSerializerFormatters() // To enable XML along with JSON;
165+
166+
// All the requests will need to be authorized.
167+
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
168+
services.AddAuthorization(options =>
169+
{
170+
options.FallbackPolicy = new AuthorizationPolicyBuilder()
171+
.RequireAuthenticatedUser()
172+
.Build();
173+
});
161174
}
162175

163176
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

src/AspNetCore.Authentication.ApiKey/ApiKeyHandlerBase.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT License. See LICENSE file in the project root for license information.
33

44
using Microsoft.AspNetCore.Authentication;
5+
using Microsoft.AspNetCore.Http;
56
using Microsoft.Extensions.DependencyInjection;
67
using Microsoft.Extensions.Logging;
78
using Microsoft.Extensions.Options;
@@ -39,6 +40,12 @@ protected ApiKeyHandlerBase(IOptionsMonitor<ApiKeyOptions> options, ILoggerFacto
3940

4041
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
4142
{
43+
if (IgnoreAuthenticationIfAllowAnonymous())
44+
{
45+
Logger.LogInformation("AllowAnonymous found on the endpoint so request was not authenticated.");
46+
return AuthenticateResult.NoResult();
47+
}
48+
4249
var apiKey = string.Empty;
4350
try
4451
{
@@ -201,5 +208,15 @@ private async Task<IApiKey> ValidateUsingApiKeyProviderAsync(string apiKey)
201208
}
202209
}
203210
}
211+
212+
private bool IgnoreAuthenticationIfAllowAnonymous()
213+
{
214+
#if (NET461 || NETSTANDARD2_0)
215+
return false;
216+
#else
217+
return Options.IgnoreAuthenticationIfAllowAnonymous
218+
&& Context.GetEndpoint()?.Metadata?.GetMetadata<Microsoft.AspNetCore.Authorization.IAllowAnonymous>() != null;
219+
#endif
220+
}
204221
}
205222
}

src/AspNetCore.Authentication.ApiKey/ApiKeyOptions.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ public class ApiKeyOptions : AuthenticationSchemeOptions
5050
/// </summary>
5151
public bool ForLegacyIgnoreExtraValidatedApiKeyCheck { get; set; }
5252

53+
#if !(NET461 || NETSTANDARD2_0)
54+
/// <summary>
55+
/// Default value is false.
56+
/// If set to true, it checks if AllowAnonymous filter on controller action or metadata on the endpoint which, if found, it does not try to authenticate the request.
57+
/// </summary>
58+
public bool IgnoreAuthenticationIfAllowAnonymous { get; set; }
59+
#endif
60+
5361
internal Type ApiKeyProviderType { get; set; } = null;
5462
}
5563
}

src/AspNetCore.Authentication.ApiKey/AspNetCore.Authentication.ApiKey.csproj

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
<Version>5.0.0</Version>
66
<RepositoryUrl>https://github.com/mihirdilip/aspnetcore-authentication-apiKey/tree/$(Version)</RepositoryUrl>
77
<PackageProjectUrl>https://github.com/mihirdilip/aspnetcore-authentication-apiKey/tree/$(Version)</PackageProjectUrl>
8-
<PackageTags>aspnetcore, security, authentication, microsoft, microsoft.aspnetcore.authentication, microsoft-aspnetcore-authentication, microsoft.aspnetcore.authentication.apikey, microsoft-aspnetcore-authentication-apikey, asp-net-core, netstandard, netstandard20, apikey-authentication, api-key-authentication, apikeyauthentication, dotnetcore, dotnetcore3.1, asp-net-core-apikey-authentication, aspnetcore-apikey-authentication, asp-net-core-authentication, aspnetcore-authentication, asp, aspnet, apikey, api-key, authentication-scheme</PackageTags>
9-
<PackageReleaseNotes>- Ability to have ApiKey in Authorization header added
10-
- Fixed extensions methods to use correct handler
11-
- Fixed issue with resolving of IApiKeyProvider implementation when using multiple schemes
8+
<PackageTags>aspnetcore, security, authentication, microsoft, microsoft.aspnetcore.authentication, microsoft-aspnetcore-authentication, microsoft.aspnetcore.authentication.apikey, microsoft-aspnetcore-authentication-apikey, asp-net-core, netstandard, netstandard20, apikey-authentication, api-key-authentication, apikeyauthentication, dotnetcore, dotnetcore3.1, net5, asp-net-core-apikey-authentication, aspnetcore-apikey-authentication, net5-apikey-authentication, asp-net-core-authentication, aspnetcore-authentication, net5-authentication, asp, aspnet, apikey, api-key, authentication-scheme</PackageTags>
9+
<PackageReleaseNotes>- Net 5.0 target framework added
10+
- IgnoreAuthenticationIfAllowAnonymous added to the ApiKeyOptions from netcoreapp3.0 onwards
1211
</PackageReleaseNotes>
13-
<Description>Easy to use and very light weight Microsoft style API Key Authentication Implementation for ASP.NET Core. It can be setup so that it can accept API Key either in Header, QueryParams or HeaderOrQueryParams.</Description>
12+
<Description>Easy to use and very light weight Microsoft style API Key Authentication Implementation for ASP.NET Core. It can be setup so that it can accept API Key either in Header, Authorization Header, QueryParams or HeaderOrQueryParams.</Description>
1413
<Authors>Mihir Dilip</Authors>
1514
<Company>Mihir Dilip</Company>
1615
<Copyright>Copyright (c) 2020 Mihir Dilip</Copyright>

0 commit comments

Comments
 (0)